S-Wing
S-Wing

Reputation: 579

Spring batch JobExecutionListener doesn't work

I've got a Spring batch job that works correctly; I've add a job listener to change the exit status of the application but the job never goes inside the listener ( beforeJob and afterJob are never called). This is a part of my code:

@Bean(name = "myJob")
public Job myJob(@Qualifier("initStep") Step initStep,
        @Qualifier("firstStep") Step firstStep,
        @Qualifier("onSuccessStep") Step onSuccessStep) {

    return jobBuilderFactory.get("myJob")
            .listener(new JobExecutionListener() {
                @Override
                public void beforeJob(JobExecution jobExecution) {

                }

                @Override
                public void afterJob(JobExecution jobExecution) {
                    ExitStatus exitStatus = jobExecution.getExitStatus() ;

                    if(exitStatus != ExitStatus.COMPLETED ){
                        System.exit(1);
                    }
                }
            })
            .start(initStep)
            .next(firstStep)
            .next(onSuccessStep)
            .build();
}

The job starts and ends correctly, but it never goes inside the listener; any suggestion?

Upvotes: 1

Views: 7196

Answers (1)

Vignesh T I
Vignesh T I

Reputation: 872

The code shared works for me. But you can try alternate implementations like below to check if that works for you,

Snippet to show a sample job config with the listener,

Job job = jobBuilderFactory.get("jobName").incrementer(new RunIdIncrementer())
    .start(step1()).next(step2()).next(step3()).next(step4).end()
    .listener(jobCompletionListener()).build();

@Bean
public JobCompletionListener jobCompletionListener() {
    return new JobCompletionListener();
}

Snippet of JobCompletionListener implementation,

public class JobCompletionListener extends JobExecutionListenerSupport {

private static final Logger logger = LoggerFactory.getLogger(JobCompletionListener.class);

   @Override
   public void afterJob(JobExecution jobExecution) {
       if (jobExecution.getStatus() == BatchStatus.COMPLETED) {
           logger.info("Job execution completed successfully");
       } else {
           logger.error("Job Execution Failed");
       }
   }
}

Upvotes: 3

Related Questions