使用 List 将对象保存为 csv 文件 FlatFileItemWriter
Save object with List as csv file FlatFileItemWriter
我有一个对象(抽象描述)
public class Book {
private String name;
private List<Author> authors;
}
public class Author {
private String name;
}
例如
new Book()
.setName("Book name1")
.setAuthors(new ArrayList(Arrays.asList(
new Author().setName("Author 1"),
new Author().setName("Author 2"))));
示例代码:
@Bean
public FlatFileItemWriter<Book> writer()
{
FlatFileItemWriter<Book> writer = new FlatFileItemWriter<>();
writer.setResource(outputResource);
writer.setAppendAllowed(true);
writer.setLineAggregator(new DelimitedLineAggregator<Book>() {
{
setDelimiter(";");
setFieldExtractor(new BeanWrapperFieldExtractor<Book>() {
{
setNames(new String[] { "name", "authors" });
}
});
}
});
return writer;
}
这样我得到结果:
Book name1;[Author(authorName=Author 1), Author(authorName=Author 2)]
但我想获取结果 csv 文件为:
Book name1;Author 1
Book name1;Author 2
帮助我理解它是如何工作的。
提前致谢。
Help me to understand, how does it work
BeanWrapperFieldExtractor
是一个字段提取器,它在输入对象的每个字段上调用 getters。这是其 Javadoc 的摘录:
Given an array of property names, it will reflectively call getters on the item
and return an array of all the values.
在您的情况下,调用字段 authors
的 getter 会导致 List
对象的 toString()
值:
[Author(authorName=Author 1), Author(authorName=Author 2)]
但是,您尝试做的实际上是一个平面图操作,因为您希望每本输入的书都写成多行,每个作者一行。有很多方法可以做到这一点,.
中描述了其中一种方法
我有一个对象(抽象描述)
public class Book {
private String name;
private List<Author> authors;
}
public class Author {
private String name;
}
例如
new Book()
.setName("Book name1")
.setAuthors(new ArrayList(Arrays.asList(
new Author().setName("Author 1"),
new Author().setName("Author 2"))));
示例代码:
@Bean
public FlatFileItemWriter<Book> writer()
{
FlatFileItemWriter<Book> writer = new FlatFileItemWriter<>();
writer.setResource(outputResource);
writer.setAppendAllowed(true);
writer.setLineAggregator(new DelimitedLineAggregator<Book>() {
{
setDelimiter(";");
setFieldExtractor(new BeanWrapperFieldExtractor<Book>() {
{
setNames(new String[] { "name", "authors" });
}
});
}
});
return writer;
}
这样我得到结果:
Book name1;[Author(authorName=Author 1), Author(authorName=Author 2)]
但我想获取结果 csv 文件为:
Book name1;Author 1
Book name1;Author 2
帮助我理解它是如何工作的。 提前致谢。
Help me to understand, how does it work
BeanWrapperFieldExtractor
是一个字段提取器,它在输入对象的每个字段上调用 getters。这是其 Javadoc 的摘录:
Given an array of property names, it will reflectively call getters on the item
and return an array of all the values.
在您的情况下,调用字段 authors
的 getter 会导致 List
对象的 toString()
值:
[Author(authorName=Author 1), Author(authorName=Author 2)]
但是,您尝试做的实际上是一个平面图操作,因为您希望每本输入的书都写成多行,每个作者一行。有很多方法可以做到这一点,