How to run Spring Batch the same way like spring.batch.job.enabled=true

Viewed 268

I am learning about spring batch and was following the guide from https://spring.io/guides/gs/batch-processing/

I figured that to stop the spring batch from starting automatically when firing up the app, I have to set spring.batch.job.enabled=false

My question is how do I manually trigger it? I tried the below to trigger the job after a return key is pressed in console but it is not working(It was working with spring.batch.job.enabled=true and without the JobLauncherController class)

@SpringBootApplication
public class BatchProcessingApplication {
public static void main(String[] args) throws Exception
    {
        SpringApplication.run(BatchProcessingApplication.class, args);
        new Scanner(System.in).nextLine();
        new JobLauncherController().launchJob();
    }
}

@Controller
public class JobLauncherController {

    @Autowired
    JobLauncher jobLauncher;

    @Autowired
    Job importUserJob;

    public void launchJob() throws Exception{
        JobParameters parameters = new JobParametersBuilder()
          .addLong("run.id", new Date().getTime()).toJobParameters();

        jobLauncher.run(importUserJob, parameters);
}
2 Answers

Make the JobLauncherController a Rest controller

@RestController
@RequestMapping("/launch/job")
public class JobLauncherController {

and make your method a Get endpoint by having a Get mapping. You can test it through postman by running a http://localhost:8080/launch/job GET Rest endpoint once you run your spring batch application and it starts up. You definitely have to have a @scheduler configured or a rest endpoint that's triggered by a human or another application to run the spring batch process appropriately. In your case since you mentioned you want to run it manually, its common to use a rest endpoint to trigger the batch job. Hope this helps.

@GetMapping
public void launchJob() throws Exception{

When you use new JobLauncherController(), you are creating the object yourself and you are not getting a bean from the Spring application context. So dependency injection is not applied to your object and collaborators are not injected. If you want to run the job manually, you can bypass the controller, something like this:

@SpringBootApplication
public class BatchProcessingApplication {

   public static void main(String[] args) throws Exception {
        new Scanner(System.in).nextLine();
        ApplicationContext context = SpringApplication.run(BatchProcessingApplication.class, args);
        Job job = context.getBean(Job.class);
        JobLauncher jobLauncher = context.getBean(JobLauncher.class);
        JobParameters parameters = new JobParametersBuilder()
          .addLong("run.id", new Date().getTime())
          .toJobParameters();

        jobLauncher.run(job, parameters);
    }
}
Related