Java Reference
In-Depth Information
Listing 4-21. Adding a Name to the Job's ExecutionContext
package com.apress.springbatch.chapter4;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.batch.item.ExecutionContext;
public class HelloWorld implements Tasklet {
private static final String HELLO_WORLD = "Hello, %s";
public RepeatStatus execute( StepContribution step,
ChunkContext context ) throws Exception {
String name =
(String) context.getStepContext()
.getJobParameters()
.get("name");
ExecutionContext jobContext = context.getStepContext()
.getStepExecution()
.getJobExecution()
.getExecutionContext();
jobContext.put(“user.name", name);
System.out.println( String.format(HELLO_WORLD, name) );
return RepeatStatus.FINISHED;
}
}
Notice that you have to do a bit of traversal to get to the job's ExecutionContext . All you're doing in
this case is going from the chunk to the step to the job, working your way up the tree of scopes. If you
look at the API for StepContext , you see that there is a getJobExecutionContext() method. This method
returns a Map<String, Object> that represents the current state of the job's ExecutionContext . Although
this is a handy way to get access to the current values, it has one limiting factor in its use: updates made
to the Map returned by the StepContext.getJobExecutionContext() method aren't persisted to the actual
ExecutionContext . Thus any changes you make to that Map that aren't also made to the real
ExecutionContext are lost in the event of an error.
Listing 4-21's example showed using the job's ExecutionContext , but the ability to obtain and
manipulate the step's ExecutionContext works the same way. In that case, you get the ExecutionContext
directly from the StepExecution instead of the JobExecution . Listing 4-22 shows the code updated to use
the step's ExecutionContext instead of the job's.
Listing 4-22. Adding a Name to the Job's ExecutionContext
package com.apress.springbatch.chapter4;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
 
Search WWH ::




Custom Search