Search code examples
springspring-batch

Getting batch job id nside ItemProcessListener in spring batch 5


My listener is as given below :

@Component
@Slf4j
public class ProcessorExecutionListener implements ItemProcessListener<OriginDAO, DestinationDAO> {


    @Override
    public void onProcessError(OriginDAO originADAO, Exception e) {
        log.error("Want to display batch job id here in the logs. Is it possible?");
    }

}

I want to display batch job id in my logs on err. Any idea? ty.


Solution

  • You can do that by making the listener step-scoped and inject the step execution in it. Here is an example:

    @Component
    @StepScope
    @Slf4j
    public class ProcessorExecutionListener implements ItemProcessListener< OriginDAO, DestinationDAO> {
    
        @Value("#{stepExecution}")
        private StepExecution stepExecution;
    
        @Override
        public void onProcessError(OriginDAO item, Exception e) {
            Long jobId = stepExecution.getJobExecution().getJobId();
            log.error("batch job id = {}", jobId);
        }
        
    }
    

    This listener should be registered in the step as a listener as well.