I'll go ahead and answer my own question. There's multiple ways to do this, but I found that saving properties and objects first to the StepExecutionContext
, then promoting them to the JobExecutionContext
after the Step completes works well. It is also documented pretty thoroughly here.
Step 1:
In your Writer / Reader declare a private StepExecution
. Then, inside your read/write method create the step context, and put your data in as a key/value pair:
ExecutionContext stepContext = this.stepExecution.getExecutionContext();
stepContext.put("someKey", someObject);
Step 2:
Add an ExecutionContextPromotionListener
to your step's bean configuration. The ExecutionContextPromotionListener
must include a String[]
property called Keys that includes the keys you wish to promote to Job scope beyond your step, similar to this implementation from a LinkedIn article:
@Bean
public ExecutionContextPromotionListener promotionListener() {
ExecutionContextPromotionListener listener = new ExecutionContextPromotionListener();
listener.setKeys( new String[] { "entityRef" } );
return listener;
}
Step 3:
You also need to add the StepExecution into your Writer before your step executes:
@BeforeStep
public void saveStepExecution( StepExecution stepExecution ) {
this.stepExecution = stepExecution;
}
Step 4:
This will give your write()
method access to the stepExecution
instance, where it can access stepContext
for you to save your data. For instance, you can write
write() {
... // write logic
ExecutionContext stepContext = this.stepExecution.getExecutionContext();
stepContext.put("keyYouWantToPutIn", theCorrespondingDataObject);
}
Finally, in your next step, you can retrieve this data (example coming directly from the Spring Batch documentation:
@BeforeStep
public void retrieveInterstepData(StepExecution stepExecution) {
JobExecution jobExecution = stepExecution.getJobExecution();
ExecutionContext jobContext = jobExecution.getExecutionContext();
this.someObject = jobContext.get("someKey");
}
This time, however, notice that it's being accessed from the jobContext
as opposed to the stepContext
- it's been promoted!