Java Reference
In-Depth Information
Listing 5-9.
Updated
HelloWorld
Tasklet
package com.apress.springbatch.chapter5;
import java.util.List;
import org.springframework.batch.core.JobInstance;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.explore.JobExplorer;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
public class HelloWorld implements Tasklet {
private static final String HELLO = "Hello, %s!";
private static final String WELCOME = "And then we have %s!";
private static final String JOB_NAME = "helloWorldJob";
private JobExplorer explorer;
public RepeatStatus execute(StepContribution stepContribution,
ChunkContext chunkContext) throws Exception {
List<JobInstance>instances =
explorer.getJobInstances(JOB_NAME, 0, Integer.MAX_VALUE);
String name = (String) chunkContext.getStepContext()
.getJobParameters()
.get("name");
if (instances != null && instances.size() > 1) {
System.out.println(String.format(WELCOME, name));
} else {
System.out.println(String.format(HELLO, name));
}
return RepeatStatus.FINISHED;
}
public void setExplorer(JobExplorer explorer) {
this.explorer = explorer;
}
}
The code in Listing 5-9 begins by obtaining all the JobInstances for
helloWorldJob
. Once it has the
list, it determines whether the job has been run before. If it has, you use the “Welcome back” message. If
this is the first time the job is being run, you use the “Hello” message.
With the code and configuration in place, run the job twice so you can see both halves of the
if
statement execute. Listing 5-10 shows the important output for each job.