Spring Batch Access to Job Parameter Inside Step

I have the following Spring Batch Job configuration:

@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 start with the 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 the ccReportId parameter from job steps?

+6
source share
1 answer

Tasklet.execute() takes a ChunkContext parameter, where Spring Batch enters all the metadata. Thus, you just need to find job parameters through these metadata structures:

 chunkContext.getStepContext().getStepExecution() .getJobParameters().getString("ccReportId"); 

or another option is to access the job parameters as follows:

 chunkContext.getStepContext().getJobParameters().get("ccReportId"); 

but this gives you an Object , and you need to pass it to a string.

+13
source

All Articles