如何在 spring 批次中在多个 ItemProcessor 运行之间共享值?

How to share value between multiple ItemProcessor runs , in spring batch?

在将记录传递给编写器之前,我必须在记录对象的 csv 文件中设置记录行。 我想要实现的是声明一个全局变量让我们说 line = 1 并且每次 itemProcessor 运行时它应该将其值分配给当前项目,并将其值增加 1 line++

如何在多个 itemProcessor 运行中共享一个变量?

如果您只需要单个 Step 中的 ExecutionContextJobExecution 如果您需要 Job 的其他 Step 中的 ExecutionContext

在您的 ItemProcessor:

中注入任一执行
@Value("#{stepExecution.jobExecution}") JobExecution jobExecution

@Value("#{stepExecution}") StepExecution stepExecution

以JobExecution为例:

@StepScope
@Bean
public MyItemProcessor myItemProcessor(@Value("#{stepExecution.jobExecution}") JobExecution jobExecution) {
    return new MyItemProcessor(jobExecution);
}

@Bean
public Step myStep() {
    return stepBuilderFactory.get("myStep")
        ...
        .processor(myItemProcessor(null))
        ...
        .build()
}

public class MyItemProcessor implements ItemProcessor<MyItem, MyItem> {

    private ExecutionContext executionContext;

    public MyItemProcessor() {
        this.executionContext = jobExecution.getExecutionContext();
    }

    @Override
    public MyItem process(MyItem item) throws Exception {
        // get the line from previous item processors, if exists, otherwise start with 0
        int line = executionContext.getInt("myLineKey", 0);
        item.setLine(line++);
        // save the line for other item processors
        item.put("myLineKey", line);
        return item;
    }

}