Spring Batch访问步骤内的作业参数

时间:2015-09-08 18:50:48

标签: java spring spring-batch

我有以下Spring Batch Job配置:

@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();
    }

}

我使用以下代码开始工作:

    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();
                }

如何从作业步骤访问ccReportId参数?

1 个答案:

答案 0 :(得分:18)

Tasklet.execute()方法接受参数ChunkContext,其中Spring Batch注入所有元数据。所以你只需要通过这些元数据结构挖掘作业参数:

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

或其他选项是以这种方式访问​​作业参数:

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

但是这会给你Object,你需要把它投射到字符串。