How to use Intercepting Job Execution in Spring Batch

For Intercepting Job Execution feature, Spring Batch provides an interface called JobExecutionListener to notify events in a Job lifecycle. So in the tutorial, JavaSampleApproach will guide how to configure Intercepting Job Execution with JobExecutionListener.

Related Posts:
1. How to start with Spring Batch using Spring Boot – Java Config
2. Spring Batch XML Config by Spring Boot
3. How to use Spring Batch Inheritance function

I. Technologies

– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.1.RELEASE
– Spring Boot: 1.5.1.RELEASE
– MySQL Database 1.4

II. Intercepting Job Execution

For Intercepting Job Execution, Spring Batch provides an interface JobExecutionListener:

Function void beforeJob(JobExecution jobExecution): is invoked before a job executes.
Function void afterJob(JobExecution jobExecution): is invoked after completion of a job.

For register a job execution listener with Java config, use:
org.springframework.batch.core.job.builder.JobBuilderHelper.listener(JobExecutionListener listener)

For XML register a job execution listener, use: listeners

III. Practice

Step to do:
– Create Spring Boot project
– Create a Job Step
– Create a JobExecutionListener
– Configure Batch Job
– Create a Launch Controller
– Run & Check result

1. Create Spring Boot project

Create a Spring Boot project with needed dependencies:

2. Create Job Step

Create a simple Job step with Reader, Writer and Processor:

3. Create a JobExecutionListener

Create a Intercepting Job Execution by implementing interface: JobExecutionListener

4. Config Batch Job

– Java Config, use:org.springframework.batch.core.job.builder.JobBuilderHelper.listener(JobExecutionListener listener)

– XML config, use: listeners

– Open file to configure database for batch job:

– Enable Batch Job config:

With XML config, need import batchjob.xml file: @ImportResource("classpath:batchjob.xml")

5. Create a Launch Controller

Create a simple controller for launching job:

6. Run & Check result

– Build & Run the project with Spring Boot mode.
– Launch the Job by a request: http://localhost:8080/launchjob

IV. Sourcecode

1. SpringBatchInterceptingJobExecution
2. SpringBatchInterceptingJobExecutionXMLConfig

By grokonez | February 24, 2017.

Last updated on June 4, 2017.

Related Posts

Got Something To Say:

Your email address will not be published. Required fields are marked *