Book Image

SPRING COOKBOOK

Book Image

SPRING COOKBOOK

Overview of this book

Table of Contents (19 chapters)
Spring Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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:

  1. Add the Spring Batch configuration class to the getServletConfigClasses()method in your class extending AbstractAnnotationConfigDispatcherServletInitializer:

    public class ServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[]{AppConfig.class, BatchConfig.class};
    }
  2. In your controller class, add a JobLauncher attribute and Job attribute both autowired:

    @Autowired
    JobLauncher jobLauncher;
    
    @Autowired
    Job job;
  3. In the controller method, define the job parameters and launch the job:

    try {
      JobParametersBuilder jobParametersBuilder...