Spring Batch: Trigger an Action When A Batch Job Fails

Spring Batch: Trigger an Action When A Batch Job Fails

When a batch job fails it’s useful to automatically send a notification or trigger some sort of an action.

Spring Batch allows registering a listener in the job configuration. Below is an example of a listener that triggers an action after a job. Using the job execution, the action can be set to only fire when the job is not complete.


@Component
public class AfterJobListener implements JobExecutionListener {

    @Autowired
    private NotificationService notificationService;

    @Override
    public void afterJob(final JobExecution jobExecution) {
        if (jobExecution.getStatus() != BatchStatus.COMPLETED) {
	    notificationService.sendNotification(); // pass data about the job here
	}
    }
}