我们可以在FlatFileItemReader的SkippedLinesCallback中使用jobContext将某些参数保存到上下文中吗,在Spring批处理中

时间:2018-08-01 10:21:51

标签: spring spring-batch

我正在使用Spring-Batch开发批处理作业。我有一个文件,其中有1行,后面是几条记录。我正在使用 FlatFileItemReader 来读取文件,同时跳过标题行并使用自定义实现读取它 LineCallbackHandler 。以下是我的读者代码段。

FlatFileItemReader<BulkRegistrationInputFileRecord> itemReader = new FlatFileItemReader<>();
    itemReader.setResource(new FileSystemResource(filePath));
    DefaultLineMapper<BulkRegistrationInputFileRecord> lineMapper = new DefaultLineMapper<>();
    DelimitedLineTokenizer delimitedLineTokenizer = new DelimitedLineTokenizer(DWJobConstants
            .BULK_REGISTRATION_DELIMITER);
    delimitedLineTokenizer.setNames(new String[]{"recordIndicator", "identification", "identificationType",
            "consumerType"
    });
    lineMapper.setLineTokenizer(delimitedLineTokenizer);
    lineMapper.setFieldSetMapper(fieldSetMapper);
    itemReader.setLineMapper(lineMapper);
    itemReader.setLinesToSkip(1);
    itemReader.setSkippedLinesCallback(skippedFileHeaderCallback);

现在,我想将一些参数(将从标头中提取)放到ExecutionContext(Job或Step?)中。但是我无法在我的 SkippedFileHeaderCallback 类中自动连接StepExecution或JobExecution的bean。

以下是我到目前为止尝试过的一切。

@Component
@StepScop

public class SkippedFileHeaderCallback implements LineCallbackHandler {

   private StepExecution stepExecution;

    @BeforeStep
    public void setStepExecution(StepExecution stepExecution) {
        this.stepExecution = stepExecution;
    }

    BulkRegistrationInputFileHeader bulkRegistrationInputFileHeader;

    @Override
    public void handleLine(String line) {
        DefaultLineMapper<BulkRegistrationInputFileHeader> lineMapper = new DefaultLineMapper<>();
        DelimitedLineTokenizer delimitedLineTokenizer = new DelimitedLineTokenizer(JobConstants
                .BULK_REGISTRATION_DELIMITER);
        delimitedLineTokenizer.setNames(new String[]{"fileHeader","bankCode"});
        lineMapper.setLineTokenizer(delimitedLineTokenizer);
        lineMapper.setFieldSetMapper(fieldSetMapper);
        try {
            bulkRegistrationInputFileHeader=lineMapper.mapLine(line,0);
            setCustomTenantContext(bulkRegistrationInputFileHeader.getBankCode());
        } catch (Exception e) {
            throw new RuntimeException("File Header Can't be parsed");
        }

    }
    private void setCustomTenantContext(String bankId){
     //Getting stepExecution as NULL   
     stepExecution.getJobExecution().getExecutionContext().put("BankId",bankId);
    }
}

在这种情况下使用JobExecutionContext的正确方法是什么。

0 个答案:

没有答案