首页 > 解决方案 > 编写器中的Spring批量读取作业参数

问题描述

我目前正在命令行中传递 spring 批处理作业参数中的文件名并运行我的作业,spring 批处理作业将查找文件并读取、处理和写入文件。我目前是读取器中的作业参数文件名并读取文件名,如何在处理器和写入器中使用相同的作业参数文件名。

标签: javaspringspring-bootjava-8spring-batch

解决方案


访问作业参数的一种方法是将 StepExecutionListener 实现到您的处理器/编写器类,以利用其覆盖的方法 beforeStep 和 afterStep,

public class TestWriter implements ItemWriter<TestData>,StepExecutionListener {

    private String filePath;

    @Override
    public void beforeStep(StepExecution stepExecution) {

        try {
            filePath = (String) stepExecution.getJobExecution().getExecutionContext()
            .get("filePath");
        } catch (Exception e) {
            logger.error("Exception while performing read {}", e);
        }
    }


    @Override
    public void write(List<? extends TestData> items) throws Exception {
        // filePath value read from the job execution can be used inside read use case impl

    }

    @Override
    public ExitStatus afterStep(StepExecution stepExecution) {
        return ExitStatus.COMPLETED;
    }
}

要将值添加到 jobExecutionContext,您可以使用如下所示,

stepExecution.getJobExecution().getExecutionContext().put("path", filePath);

推荐阅读