Spring 批处理下一步如何在 ExecutionContext 中设置文件路径

Spring Batch how to set filepath in ExecutionContext for next step

我有一个 spring 批处理工作流,我从平面 csv 文件中读取并将其写入 csv 文件。

这是我的 ItemWriter 的样子:

@Configuration
public class MyCSVFileWriter implements ItemWriter<RequestModel> {

    private final FlatFileItemWriter<RequestModel> writer;

    private ExecutionContext jobContext;

    public MyCSVFileWriter() throws Exception {

        this.writer = new FlatFileItemWriter<>();

        DelimitedLineAggregator<RequestModel> lineAggregator = new DelimitedLineAggregator<>();

        BeanWrapperFieldExtractor<RequestModel> extractor = new BeanWrapperFieldExtractor<>();
        extractor.setNames(new String[]{"id", "source", "date"});

        lineAggregator.setFieldExtractor(extractor);

        this.writer.setLineAggregator(lineAggregator);
        this.writer.setShouldDeleteIfExists(true);

        this.writer.afterPropertiesSet();
    }

    @Override
    public void write(List<? extends RequestModel> items) throws Exception {
        this.writer.open(jobContext);
        this.writer.write(items);
    }

    @BeforeStep
    public void beforeStepHandler(StepExecution stepExecution) {
        JobExecution jobExecution = stepExecution.getJobExecution();
        jobContext = jobExecution.getExecutionContext();

        this.writer.setResource(new FileSystemResource(getRequestOutputPathResource(jobContext)));
    }

    private String getRequestOutputPathResource(ExecutionContext jobContext) {
        //***
        return resourcePath;
    }

}

我使用 executionContext 提取一些数据,用于为我的作者计算 resourcePath

写入后的下一步是将上一步写入的文件上传到远程服务器。为此,我需要存储计算出的文件路径并将其存储在 ExecutionContext 中,并使其在下一步中可用。

最好的方法是什么?我应该在 @AfterStep 处理程序中执行此操作吗?

Should I be doing this in a @AfterStep handler?

是的,这是一个不错的选择。您可以将已写入的文件路径存储在作业执行上下文中,并在下一步上传文件时从那里读取它。