Java Reference
In-Depth Information
public RepeatStatus execute( StepContribution step,
ChunkContext context ) throws Exception {
String name =
(String) context.getStepContext().getJobParameters().get("name");
System.out.println( String.format(HELLO_WORLD, name) );
return RepeatStatus.FINISHED;
}
}
Although Spring Batch stores the job parameters in an instance of the
JobParameter
class, when you
obtain the parameters this way
getJobParameters()
returns a
Map<String, Object>
. Because of this, the
previous cast is required.
Listing 4-9 shows how to use Spring's late binding to inject job parameters into components without
having to reference any of the
JobParameters
code. Besides the use of Spring's EL (Expression Language)
to pass in the value, any bean that is going to be configured with late binding is required to have the
scope set to
step
.
Listing 4-9.
Obtaining Job Parameters via Late Binding
<bean id="helloWorld" class="com.apress.springbatch.chapter4.HelloWorld"
scope="step">
<property name="name" value="#{jobParameters[name]}"/>
</bean>
It's important to note that in order for the configuration in Listing 4-9 to work, the
HelloWorld
class
needs to be updated to accept the new parameter. Listing 4-10 shows the updated code for this method
of parameter association.
Listing 4-10.
Updated
HelloWorld
Tasklet
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";
private String name;
public RepeatStatus execute( StepContribution step,
ChunkContext context ) throws Exception {
String name =
(String) context.getStepContext().getJobParameters().get("name");
System.out.println( String.format(HELLO_WORLD, name) );
return RepeatStatus.FINISHED;
}