15

I have a Spring Batch application, which I start with the CommandLineJobRunner. But now I have to embed this application into our corporate environment. There we have an own Launcher application which I have to use. For this launcher application I need a startup class with a main method which will be called at startup and where I would have to launch Spring Batch.

Is the only way to manually assign a JobLauncher and run the Job with this launcher or is there a class in Spring Batch which would support that (or do someone know a sample)?

Sled
  • 18,541
  • 27
  • 119
  • 168
dunni
  • 43,386
  • 10
  • 104
  • 99

3 Answers3

16

Using a Spring Boot Application if you don't want to use the CommandLineRunner (for some reason or if you need some custom logic), you can always do something like :

public static void main(String[] args) {

    SpringApplication app = new SpringApplication(YourApplication.class);
    app.setWebEnvironment(false);
    ConfigurableApplicationContext ctx = app.run(args);

    JobLauncher jobLauncher = ctx.getBean(JobLauncher.class);
    Job job = ctx.getBean("your-job-here", Job.class);
    JobParameters jobParameters = new JobParametersBuilder().toJobParameters();


    JobExecution jobExecution = jobLauncher.run(job, jobParameters);
    BatchStatus batchStatus = jobExecution.getStatus();
}
Eric Hudon
  • 161
  • 1
  • 3
  • I tried with this approach, but somehow context could not find bean of "your-job-here" despite of the fact I can see that bean was initialised by Spring container :(. Any idea why? – Vishal Dec 08 '17 at 15:29
  • 1
    It work for me well. I made on change to stop default execution of Job. Added line in application.properties :- spring.batch.job.enabled=false – skvp Feb 07 '19 at 07:17
12

Yes, you can launch your job programmatically. If you see in the source of CommandLineJobRunner, the main method just create a Spring context and use the launcher to run the job. So you can do this in your new application.

skaffman
  • 398,947
  • 96
  • 818
  • 769
Vincent Devillers
  • 1,628
  • 1
  • 11
  • 17
6

JobLauncher can be used to invoke the Job programatically. JobLauncher can be autowired in your Servlet/Controller if you're looking for a way to trigger jobs from a webapp:

http://docs.spring.io/spring-batch/reference/htmlsingle/#runningJobsFromWebContainer

Community
  • 1
  • 1
Sathish
  • 20,660
  • 24
  • 63
  • 71