Search code examples
javaspring-batchlistenerorder-of-execution

Spring Batch : Execution order for multiple JobExecutionListener instances for a single job


Given a Spring Batch job that has a list of JobExecutionListener instances configured for it, what is the execution order for each of the listeners. Example :

<job id="myJob" xmlns="http://www.springframework.org/schema/batch">

        <batch:listeners>
            <batch:listener ref="myJobExecutionListener1" />
            <batch:listener ref="myJobExecutionListener2" />
            <batch:listener ref="myJobExecutionListener3" />
            <batch:listener ref="myJobExecutionListener4" />                
        </batch:listeners>

       <!-- job config continues -->
</job>

In the above example, is there a guarentee that the listeners will be executed in the order of configuraiton or will the listeners be executed in a random order. I tried looking through the Spring Batch reference documentation but I could not find this documented as far as my research goes.


Solution

  • Listeners will be executed in their declaration order. In your example, they will be called in the following sequence:

    myJobExecutionListener1.beforeJob
    myJobExecutionListener2.beforeJob
    myJobExecutionListener3.beforeJob
    myJobExecutionListener4.beforeJob
    
    // .. job output
    
    myJobExecutionListener4.afterJob
    myJobExecutionListener3.afterJob
    myJobExecutionListener2.afterJob
    myJobExecutionListener1.afterJob