Search code examples
spring-batchspring-cloud

How to explicitly configure TaskBatchExecutionListener in my spring batch application


My spring batch application is not inserting relationship between task and job in TASK_TASK_BATCH table.

Spring doc says :

Associating A Job Execution To The Task In Which It Was Executed Spring Boot provides facilities for the execution of batch jobs easily within an über-jar. Spring Boot’s support of this functionality allows for a developer to execute multiple batch jobs within that execution. Spring Cloud Task provides the ability to associate the execution of a job (a job execution) with a task’s execution so that one can be traced back to the other.

This functionality is accomplished by using the TaskBatchExecutionListener. By default, this listener is auto configured in any context that has both a Spring Batch Job configured (via having a bean of type Job defined in the context) and the spring-cloud-task-batch jar is available within the classpath. The listener will be injected into all jobs."

I have all the required jars in my classpath.It's just that I am creating jobs and tasklets dynamically so not using any annotation. As per the doc TaskBatchExecutionListener is responsible for creating mapping in TASK_TASK_BATCH table by calling taskBatchDao's saveRelationship method.

I am just not able to figure out how to configure TaskBatchExecutionListener explicitly in my spring batch application.


Solution

  • If you have the org.springframework.cloud:spring-cloud-task-batch dependency, and the annotation @EnableTask is present, then your application context contains a TaskBatchExecutionListener bean that you can inject into your class that dynamically creates the jobs and tasklets.

    That might look similar to this:

        @Autowired
        JobBuilderFactory jobBuilderFactory;
    
        @Autowired
        TaskBatchExecutionListener taskBatchExecutionListener;
    
        Job createJob() throws Exception {
            return jobBuilderFactory
                    .get("myJob")
                    .start(createStep())
                    .listener(taskBatchExecutionListener)
                    .build();
        }
    

    I hope that helps. Otherwise please share some minimal code example to demonstrate what you're trying to do.