使用 BeanWrapperFieldExtractor 从子类对象获取属性

Get properties from subclass object using BeanWrapperFieldExtractor

在我的 Spring 批处理应用程序中,我有以下 POJO 类:

public class School {
    private String schoolName;
    private String schoolAddress;
    private ClassDetails classDetails;
}

public class ClassDetails {
    private String className;
    private String totalCountStudents;
    private SectionDetails sectionDetails;
}

public class SectionDetails {
    private String sectionName;
    private String totalSubjects;
}

我编写了以下 FlatFileItemWriter 以从 School 对象获取属性。

public FlatFileItemWriter<School> write() throws Exception {
    FlatFileItemWriter<School> flatFileWriter = new FlatFileItemWriter<School>();
    flatFileWriter.setResource(new FileSystemResource("C:\u01\SchoolDetails.txt"));
    flatFileWriter.setName("School-File-Writer");
    flatFileWriter.setAppendAllowed(true);
    flatFileWriter.setLineSeparator("\n");
    flatFileWriter.setHeaderCallback(writer -> writer.write(columnHeaders()));
    flatFileWriter.setLineAggregator(new DelimitedLineAggregator<School>() {
        {
            setDelimiter("^");
            setFieldExtractor((FieldExtractor<School>) schoolFieldExtractor());
        }
    });
    return flatFileWriter;
}
    
private BeanWrapperFieldExtractor<School> schoolFieldExtractor() {
    return new BeanWrapperFieldExtractor<School>() {
        {
            String[] columnValuesMapper = new String[] { 
                    "schoolName", "schoolAddress"
            };
            setNames(columnValuesMapper);
        }
    };
}

目前我发送的文件有schoolName, schoolAddress。但我想从 sub类 中获取所有属性以及 BeanWrapperFieldExtractor 中的学校对象。我将发送的最终输出文件应包含 schoolName、schoolAddress、className、totalCountStudents、sectionName、totalSubjects。

我不确定该怎么做。任何帮助,将不胜感激。提前致谢!

BeanWrapperFieldExtractor 支持嵌套属性的点分符号,因此您可以按如下方式定义 schoolFieldExtractor

private BeanWrapperFieldExtractor<School> schoolFieldExtractor() {
    return new BeanWrapperFieldExtractor<School>() {
        {
            String[] columnValuesMapper = new String[] { 
                "schoolName", "schoolAddress",
                "classDetails.className", "classDetails.totalCountStudents",
                "classDetails.sectionDetails.sectionName", "classDetails.sectionDetails.totalSubjects",
            };
            setNames(columnValuesMapper);
        }
    };
}