Home > database >  How to execute a Spring Batch job from a Spring Boot app
How to execute a Spring Batch job from a Spring Boot app

Time:11-18

I have two spring apps. First one is a Spring Boot (app A) and the other is a standalone Spring Batch (app B) app.

Usually, I am using a script to execute the Spring Batch (app B) jar and in the main method, I will write the jobs that I want to run.

 ApplicationContext context = SpringApplication.run(RacerBatchApp.class, args);
    JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher");
    try {
        jobLauncher.run((Job) context.getBean("JOB NAME -> XXX"), new JobParametersBuilder().addLong("job.key", System.currentTimeMillis()).toJobParameters());
    } catch (BeansException | JobExecutionAlreadyRunningException | JobRestartException | JobInstanceAlreadyCompleteException | JobParametersInvalidException e) {
        e.printStackTrace();
    }

I have a new requirement to launch a specific job in app B via app A. Basically app A Spring Boot will execute the standalone app B jar and job name XXX (hope I am clear)

Also, I don’t want to add Spring Batch dependence to the Spring Boot app.

How can I do that?

Thank you

CodePudding user response:

You can pass the job name as an argument to appA, and use it in the main method to get the job by name from the application context:

java -jar appA.jar job.name=myJob

Then in the main method:

String jobName = ..; // get job.name from application arguments;
Job job = context.getBean(jobName, Job.class);
// run the job
...

That said, I would make appB a Boot Batch app and just run:

java -jar appB.jar --spring.batch.job.names=myJob
  • Related