I have a following Spring Batch Job config:
@Configuration
@EnableBatchProcessing
public class JobConfig {
@Autowired
private JobBuilderFactory jobBuilderFactory;
@Autowired
private StepBuilderFactory stepBuilderFactory;
@Bean
public Job job() {
return jobBuilderFactory.get("job")
.flow(stepA()).on("FAILED").to(stepC())
.from(stepA()).on("*").to(stepB()).next(stepC())
.end().build();
}
@Bean
public Step stepA() {
return stepBuilderFactory.get("stepA").tasklet(new RandomFailTasket("stepA")).build();
}
@Bean
public Step stepB() {
return stepBuilderFactory.get("stepB").tasklet(new PrintTextTasklet("stepB")).build();
}
@Bean
public Step stepC() {
return stepBuilderFactory.get("stepC").tasklet(new PrintTextTasklet("stepC")).build();
}
}
I'm starting the job with a following code:
try {
Map<String,JobParameter> parameters = new HashMap<>();
JobParameter ccReportIdParameter = new JobParameter("03061980");
parameters.put("ccReportId", ccReportIdParameter);
jobLauncher.run(job, new JobParameters(parameters));
} catch (JobExecutionAlreadyRunningException | JobRestartException | JobInstanceAlreadyCompleteException
| JobParametersInvalidException e) {
e.printStackTrace();
}
How to access ccReportId
parameter from job steps ?
JobParameters can be used for identification or even as reference data during the job run. They have reserved names, so to access them we can use Spring Expression Language. For example to access a property 'abc' on job parameters: we can access it using the syntax #{jobParameters[abc]} .
Passing data between steps. In Spring Batch, ExecutionContext of execution context that can be used in the scope of each step and job is provided. By using the execution context, data can be shared between the components in the step.
Spring Batch uses a 'Chunk-oriented' processing style within its most common implementation. Chunk oriented processing refers to reading the data one at a time and creating 'chunks' that are written out within a transaction boundary.
Tasklet.execute()
method takes parameter ChunkContext
, where Spring Batch injects all the metadata. So you just need to dig into job parameters via these metadata structures:
chunkContext.getStepContext().getStepExecution()
.getJobParameters().getString("ccReportId");
or other option is to access job parameters map this way:
chunkContext.getStepContext().getJobParameters().get("ccReportId");
but this gives you Object
and you need to cast it to string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With