Search code examples
springspring-batchspring-transactions

Control step level execution in spring batch


Is it possible to execute a step or skip it and proceed to next step depending on some condition in spring batch. E.g. there are 5 steps in a batch job, and before every step execution we need to check whether to skip it or not depending on value of a column in database. Requirement is to create a generic logic either through listeners or an other way that can control the step executions at run time?

I need to populate the next attribute at runtime. Sample xml:

    <batch:step id="step1" next="stepdecision">
        <batch:tasklet ref="tasklet1" />
    </batch:step>

    <batch:step id="step2" next="stepdecision">
        <batch:tasklet ref="tasklet1" />
    </batch:step>

    <batch:step id="step3" next="stepdecision">
        <batch:tasklet ref="tasklet1" />
    </batch:step>

    <batch:step id="step4" next="stepdecision">
        <batch:tasklet ref="tasklet1" />
    </batch:step>

    <batch:decision id="stepdecision" decider="decider">
        <batch:next on="next" to="#{jobExecutionContext[nextStep]}" />
    </batch:decision>

</batch:job>

<bean id="decider" class="com.bmo.apms.batch.StepFlowDecider">
</bean>
<bean id="tasklet1" class="com.bmo.apms.batch.TestTasklet" />

But it is throwing exception: Configuration problem: The element [step2] is unreachable|

I think spring doesn't allow to bind next attribute at run time. Please advice.


Solution

  • I achieved this b creating a decider that finds the next step. Every step's next attribute is he decider which forwards it to the actual the step at run-time.

        <batch:decision id="stepdecision" decider="decider">
            <batch:next on="step1" to="step1" />
            <batch:next on="step2" to="step2" />
            <batch:next on="step3" to="step3" />
            <batch:next on="step4" to="step4" />
            <batch:end on="end" />
        </batch:decision>
    
    
    <batch:next on="step3" to="step3" />
            <batch:next on="step4" to="step4" />
            <batch:end on="end" />
        </batch:decision>
    
        <batch:step id="step1" next="stepdecision">
            <batch:tasklet ref="tasklet1" />
        </batch:step>
    
        <batch:step id="step2" next="stepdecision">
            <batch:tasklet ref="tasklet1" />
        </batch:step>
    
        <batch:step id="step3" next="stepdecision">
            <batch:tasklet ref="tasklet1" />
        </batch:step>
    
        <batch:step id="step4" next="stepdecision">
            <batch:tasklet ref="tasklet1" />
        </batch:step>