Run Spring Batch Job programmatically?

dunni picture dunni · May 10, 2011 · Viewed 31.3k times · Source

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)?

Answer

Eric Hudon picture Eric Hudon · May 2, 2016

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();
}