I have a spring batch program where execution flows of various steps are defined via xml files. One of these xml files is structured something like this.
<step id="step1" next="step2">
<!-- Configuration of step 1 -->
</step>
<step id="step2" next="step3">
<!-- Configuration of step 2 -->
</step>
<step id="step3" next="step4">
<!-- Configuration of step 3 -->
</step>
<step id="step4" next="step5">
<!-- Configuration of step 4 -->
</step>
<step id="step5" next="step6">
<!-- Configuration of step 5 -->
</step>
<step id="step6" next="step7">
<!-- Configuration of step 6 -->
</step>
<step id="step7" next="step8">
<!-- Configuration of step 7 -->
</step>
<step id="step8">
<!-- Configuration of step 8 -->
</step>
One of the last steps, let's say step 7, is a step that should always be performed, even if one of the previous steps fails, as it takes care of deleting temporary files that were generated during the execution of the flow. At the moment, when one of steps 1 to 6 generates an exception, step 7 is not reached, so the files to be deleted have to be deleted manually. I should make sure that step 7 is executed both when all the previous steps succeed and when one of them generates an exception that stops the program. Step 8, on the other hand, should be executed only when none of the previous steps generates an exception. Searching the web, it seems that it is conceivable to use listeners to achieve the desired behavior, but I would like to understand how to configure it for the purpose or if there are other more suitable ways.
If your requirement is only to delete temporary files created by steps no matter the exit status of those steps is, then a JobExecutionListener#afterJob
is a good option. This listener is always executed.
However, if you want to introduce a complex flow of execution with conditional/branching like step 7, is a step that should always be performed, even if one of the previous steps fails
or Step 8, on the other hand, should be executed only when none of the previous steps generates an exception
, then you need to define a job execution Flow
, as described in this section: Controlling Step Flow