Java Reference
In-Depth Information
How It Works
Launching a Job with Parameters
A
job
is a prototype of a
JobInstance
.
JobParameters
are used to provide a way of identifying a unique
run of a
job
(a
JobInstance
). These
JobParameters
allow you to give input to your batch process, just
as you would with a method definition in Java. You've seen the
JobParameters
in previous examples,
but not in detail. The
JobParameters
object is created as you launch the
job
using the
JobLauncher
. To
launch a
job
called
dailySalesFigures
, with the date for the job to work with, you would write something
like this:
ClassPathXmlApplicationContext classPathXmlApplicationContext = new
ClassPathXmlApplicationContext("solution2.xml");
classPathXmlApplicationContext.start();
JobLauncher jobLauncher = (JobLauncher) classPathXmlApplicationContext.
➥
getBean("jobLauncher");
Job job = (Job) classPathXmlApplicationContext.getBean("dailySalesFigures");
jobLauncher.run(job, new JobParametersBuilder().addDate( "date",
DateUtils.truncate(new Date(), Calendar.DATE)).toJobParameters());
Accessing JobParameters
Technically, you can get at
JobParameters
via any of the
ExecutionContexts
(
step
,
job
, and so on). Once
you have it, you can access the parameters in a type-safe way by calling
getLong()
,
getString()
, and so
on. A simple way to do this is to bind to the
@BeforeStep
event, save the
StepExecution
, and iterate over
the parameters this way. From here, you can inspect the parameters and do anything you want with
them. Let's look at that in terms of the
ItemProcessor
you wrote earlier:
// …
private StepExecution stepExecution;
@BeforeStep
public void saveStepExecution(StepExecution stepExecution) {
this.stepExecution = stepExecution;
}
public UserRegistration process(UserRegistration input) throws Exception {
Map<String, JobParameter> params = stepExecution.getJobParameters().
➥
getParameters();
// iterate over all of the parameters
for (String jobParameterKey : params.keySet()) {
System.out.println(String.format("%s=%s", jobParameterKey,
params.get(jobParameterKey).getValue().toString()));
}
// access specific parameters in a type safe way
Date date = stepExecution.getJobParameters().getDate("date");
// etc …
}
Search WWH ::
Custom Search