弹簧批次访问步骤内的作业参数

2022-09-04 00:56:05

我有一个以下春季批处理作业配置:

@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

Tasklet.execute()方法采用参数,其中 Spring Batch 注入所有元数据。因此,您只需要通过以下元数据结构深入了解作业参数:ChunkContext

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

或者其他选项是通过以下方式访问作业参数映射:

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

但这给了你,你需要把它扔到字符串。Object


答案 2

推荐