Spring Batch accessing job parameter inside step

℡╲_俬逩灬. 提交于 2019-12-10 12:37:38

问题


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 ?


回答1:


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.



来源:https://stackoverflow.com/questions/32465142/spring-batch-accessing-job-parameter-inside-step

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!