Executing a job from a controller method
It's convenient to launch a job from a controller method when that job is triggered by a user action. For example, launching a job to process a video just uploaded by the user.
Getting ready
We'll use the job defined in the Creating a job recipe.
How to do it…
Follow these steps to execute the job from a controller method:
Add the Spring Batch configuration class to the
getServletConfigClasses()
method in your class extendingAbstractAnnotationConfigDispatcherServletInitializer
:public class ServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getServletConfigClasses() { return new Class<?>[]{AppConfig.class, BatchConfig.class}; }
In your controller class, add a
JobLauncher
attribute andJob
attribute both autowired:@Autowired JobLauncher jobLauncher; @Autowired Job job;
In the controller method, define the job parameters and launch the job:
try { JobParametersBuilder jobParametersBuilder...