在Spring Batch中动态地绞接到多个文件

时间:2018-06-27 15:31:36

标签: spring-boot spring-batch

在Spring批处理中,我将文件写入配置为:

@Bean
public FlatFileItemWriter<MyObject> flatFileItemWriter() throws Exception{
    FlatFileItemWriter<MyObject> itemWriter = new FlatFileItemWriter();
    // pass through aggregator just calls toString on any item pass in. 
    itemWriter.setLineAggregator(new PassThroughLineAggregator<>());

    String outputPath = File.createTempFile("output", ".out").getAbsolutePath();
    System.out.println(">>output path=" + outputPath);

    itemWriter.setResource(new FileSystemResource(outputPath));
    itemWriter.afterPropertiesSet();

    return itemWriter;
}

如果MyObject是一个复杂的结构,该结构会随配置设置等而变化,并且我想将该结构的不同部分生成到不同的文件,会发生什么。

我该怎么做?

1 个答案:

答案 0 :(得分:1)

您看过CompositeItemWriter吗?根据需要,您可能需要在阅读器中包含CompositeLineMapper以及ClassifierCompositeItemProcessor。

下面是CompositeItemWriter的示例

@Bean
public ItemWriter fileWriter() {
    CompositeItemWriter compWriter = new CompositeItemWriter();

    FlatFileItemWriter<MyObject_data> dataWriter = new FlatFileItemWriter<MyObject_data>();
    FlatFileItemWriter<MyObject_otherdata> otherWriter = new FlatFileItemWriter<MyObject_otherdata>();

    List<ItemWriter> iList = new ArrayList<ItemWriter>();
    iList.add(dataWriter);
    iList.add(otherWriter);
    compWriter.setDelegates(iList);

    return compWriter;
}