想象一下一个带有3个字段的Menu.java pojo:id,name和telephone。
我使用Spring Batch 3.我的处理器返回一个List。我想在文件中写下列表中每个对象的这些值。
如果菜单不是列表,那么这将是我的作家类:
@Bean(name="MyWriter")
@SphynxBatchStepScope
public FlatFileItemWriter<Menu> myWriter() String fileOutputName) {
FlatFileItemWriter<Menu> writer = new FlatFileItemWriter<Menu>();
writer.setResource(new FileSystemResource("test.txt")));
DelimitedLineAggregator<Menu> delLineAgg = new DelimitedLineAggregator<Menu>();
delLineAgg.setDelimiter(" ");
BeanWrapperFieldExtractor<Menu> fieldExtractor = new BeanWrapperFieldExtractor<Menu>();
fieldExtractor.setNames(new String[] {"id", "name", "telephone"});
delLineAgg.setFieldExtractor(fieldExtractor);
writer.setLineAggregator(delLineAgg);
writer.setHeaderCallback(header());
writer.setFooterCallback(footer());
writer.setEncoding("UTF-8");
return writer;
}
但是,如果我想将这个类转换为使用List,我该怎么办呢?
我无法找到任何解决方案。只有这个:
Using an ItemWriter with List of Lists
但我不知道如何实现这一点。例如,在何处以及如何调用setDelegate方法。或者,当我需要将我的&#34; id&#34;,&#34; name&#34;,&#34;电话&#34;序列
请问,是否有人知道带有List的自定义Writer的代码示例?
提前致谢
答案 0 :(得分:0)
你的作家将保持原样但被ListUnpackingItemWriter
包裹。
// NOTE: this will now be the delegate used by the delegating writer.
// It will be injected to the delegating writer.
@Bean(name="MyDelegateWriter")
@SphynxBatchStepScope
public FlatFileItemWriter<Menu> myWriter(String fileOutputName) {
FlatFileItemWriter<Menu> writer = new FlatFileItemWriter<Menu>();
writer.setResource(new FileSystemResource("test.txt")));
DelimitedLineAggregator<Menu> delLineAgg = new DelimitedLineAggregator<Menu>();
delLineAgg.setDelimiter(" ");
BeanWrapperFieldExtractor<Menu> fieldExtractor = new BeanWrapperFieldExtractor<Menu>();
fieldExtractor.setNames(new String[] {"id", "name", "telephone"});
delLineAgg.setFieldExtractor(fieldExtractor);
writer.setLineAggregator(delLineAgg);
writer.setHeaderCallback(header());
writer.setFooterCallback(footer());
writer.setEncoding("UTF-8");
return writer;
}
// NOTE: now this "MyWriter" will be used by your job
@Bean(name="MyWriter")
@SphynxBatchStepScope
public ListUnpackingItemWriter(@Qualifier("MyDelegateWriter") FlatFileItemWriter<Menu> delegate) {
ListUnpackingItemWriter<List<Menu>> writer = new ListUnpackingItemWriter<>();
writer.setDelegate(delegate);
return writer;
}