简体   繁体   中英

Spring Batch, variable through the steps of a job

I'm trying to create a job in Spring Batch but I can't find something.. My program looks like that :

  • A tasklet wich create a list of ids
  • A Reader that use this list to get a String in the database and concatenated them
  • A Writer that take this String and write it in a file
  • A tasket that use the list of ids and update the database.

First, is it the best choice for the structure of my batch ?

The main problem is that I don't know how to get the list of ids in the Reader and in the last Tasklet. I'm using Spring and I've tried this :

    <bean id="idList" class="java.util.ArrayList" scope="job" />

    <bean id="myFirstTasklet" class="myFirstTasklet"
        <property name="idList" ref="idList" />
    </bean>

    <bean id="myReader" class="myReader"
        <property name="idList" ref="idList" />
    </bean>

    <bean id="mySecondTasklet" class="mySecondTasklet"
        <property name="idList" ref="idList" />
    </bean>

Can my list be updated by the tasklet before the creation of the Reader and the second tasklet ?

You can put the value in ExecutionContext of tasklet and then later retrieve it in other tasklet. See the code below:

Inside 1st tasklet-

public RepeatStatus execute(StepContribution stepContribution,
        ChunkContext chunkContext) throws Exception {

//Putting value in Execution Context
chunkContext.getStepContext().getStepExecution().getJobExecution()
            .getExecutionContext()
            .put(Constants.DATA_LIST, idList);

}

Inside 2nd tasklet:

public RepeatStatus execute(StepContribution contribution,
        ChunkContext chunkContext) throws Exception {

//Retrieving value from Execution context
(ArrayList) chunkContext.getStepContext()
            .getStepExecution().getJobExecution().getExecutionContext()
            .get(Constants.DATA_LIST);

 }

Also ensure to mark the scope of your tasklet as step:

<bean id="mySecondTasklet" class="mySecondTasklet" scope="step" >

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM