我有以下Pojo类:
public class Student {
String name;
Integer age;
List<Interest> interests;
}
public class Interest {
String name;
Date createdAt;
}
我有下面的CSV文件与标题到位:
NAME,AGE,INTEREST_1,INTEREST_2,INTEREST_3,INTERESTS_ADDITIONAL
是否有可能有一个FlatFileItemWriter,将写入基于该头的csv文件?
每个学生的兴趣列表中的前3个兴趣将放在第3、4和5列,如果列表中有超过3个,只需将他们的名字添加到第6列。
到目前为止,我一直使用类似于这样的FlatFileItemWriter:
public FlatFileItemWriter<Student> writer() {
FlatFileItemWriter<Student> writer = new FlatFileItemWriter<>();
writer.setResource(outputResource);
writer.setAppendAllowed(true);
writer.setLineAggregator(new DelimitedLineAggregator<Student>() {
{
setDelimiter(",");
setFieldExtractor(new BeanWrapperFieldExtractor<Student>() {
{
setNames(new String[] { "name", "age", "interest" });
}
});
}
});
return writer;
}
但是这对感兴趣的列表不起作用。如有任何帮助,我将不胜感激。
谢谢。
您可以编写自定义的FieldExtactor
来根据需要提取字段。下面是一个简单的例子:
@Bean
public FlatFileItemWriter<Student> itemWriter() {
FlatFileItemWriter<Student> writer = new FlatFileItemWriter<>();
writer.setResource(outputResource);
writer.setAppendAllowed(true);
writer.setLineAggregator(new DelimitedLineAggregator<Student>() {
{
setDelimiter(",");
setFieldExtractor(new FieldExtractor<Student>() {
@Override
public Object[] extract(Student student) {
List<Object> fields = new ArrayList<>();
fields.add(student.getName());
fields.add(student.getAge());
// add interests as needed to the list
return fields.toArray();
}
});
}
});
return writer;
}