Spring Batch: persisting data in the Step Execution Context

3 April 2012, by Baptiste Autin

In the method execute() of a Tasklet, if you want to store data in the ExecutionContext of the current Step, be careful.
Don’t write:

chunkContext.getStepContext().getStepExecutionContext().put("myKey", "myValue");

Instead write:

chunkContext.getStepContext().getStepExecution().getExecutionContext().put("mode", "test");

Indeed, getStepExecutionContext() returns a unmodifiable collection. So you are good for a java.lang.UnsupportedOperationException at java.util.Collections$UnmodifiableMap.put(Collections.java:1285)
if you try to modify what it returns.

Note: if you use an ItemWriter instead of a Tasklet, you can’t go wrong, as you have to explicitly add a listener with a @BeforeStep:

private StepExecution stepExecution;

public void saveStepExecution(StepExecution stepExecution) {
    this.stepExecution = stepExecution;


this.stepExecution.getExecutionContext().put("someKey", "myValue");

Laisser une réponse

«     »