在 Spring 批处理 FileHeaderFieldSetMapper 中使用工厂模式

Use of Factory Pattern in Spring Batch FileHeaderFieldSetMapper

我正在设置一个 Spring 批处理作业来处理一个多记录文件。其中一条记录具有以下结构。

Ind,RecCode,AccNum,RecTypeDesc,EffectiveDate,CreditAmount,DebitAmount,BatchNumber,NumberOfTrasactions 
5, 20, 100, prl, 12084, as0, 0, 3, 1

根据 RecordCode 字段中的值,它将是付款记录或冲销记录。

我正在设置 PatternMatchingCompositeLineMapper 来读取文件中的记录类型。我创建了以下 2 个 FieldSetMapper 实现 classes

@Component("paymentBatchFieldSetMapper")
public class  PaymentBatchFieldSetMapper implements FieldSetMapper<PaymentBatch> {

    @Override
    public PaymentBatch mapFieldSet(FieldSet fieldSet) throws BindException {
        // TODO Auto-generated method stub
        return null;
    }
}

第二个是,

@Component("reversalBatchFieldSetMapper")
public class  ReversalBatchFieldSetMapper implements FieldSetMapper<PaymentBatch> {

    @Override
    public PaymentBatch mapFieldSet(FieldSet fieldSet) throws BindException {
        // TODO Auto-generated method stub
        return null;
    }
}

我创建了一个工厂 class 如下 return 以上 2 之一

@Component("achBatchFieldSetMapperFactory")
public class ACHBatchFieldSetMapperFactory {

    @Autowired
    private ApplicationContext applicationContext;

    public FieldSetMapper<? extends AbstractACHBatch> getFieldSetMapper(RecordTypeDescription recordTypeDescription) {
        FieldSetMapper<? extends AbstractACHBatch> fieldSetMapper = null;
        switch(recordTypeDescription) {
        case PAYMENT:
            fieldSetMapper = applicationContext.getBean(PaymentBatchFieldSetMapper.class);
            break;
        case REVERSAL:
            fieldSetMapper = applicationContext.getBean(ReversalBatchFieldSetMapper.class);
            break;
        }
        return fieldSetMapper;
    }
}

下面是要注入PatternMatchingCompositeLineMapper 的地图对象的bean 配置。

@Bean
public Map<String, LineTokenizer> fieldSetMapperMap(FileHeaderFieldSetMapper fileHeaderFieldSetMapper, PaymentBatchFieldSetMapper paymentBatchFieldSetMapper,
        ReversalBatchFieldSetMapper reversalBatchFieldSetMapper) {
    Map<String, FieldSetMapper> map = new HashMap<String, FieldSetMapper>();
    map.put("1*", fileHeaderFieldSetMapper);
    map.put("5*", ?????);                   
}

是否有可能根据文件中的记录使用工厂 return 所需的 FieldSet 映射器?

项目 reader 设计为一次 return 一种类型的项目。假设我们设法根据 RecordCode 字段将记录映射到 PaymentBatchReversalBatch,这意味着在映射发生后,ItemReader 将 return两种。这在设计上是不可能的。

你可以做的是创建一个与输入文件中的字段具有一对一映射的 POJO,然后使用 ClassifierCompositeItemProcessor 根据其类型处理每个项目(分类器将基于你的情况下的 RecordTypeDescription 枚举。

注意: 当然技术上可以忘记 ItemReader<T> 接口的泛型类型并使项目 reader return Objects,但这需要在您的处理器中丑陋地使用 instanceof 来确定记录类型。我强烈建议不要使用这种方法。