Search code examples
springspring-batchbatch-processing

Get properties from subclass object using BeanWrapperFieldExtractor


In my Spring batch application I have the following POJO classes:

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;
}

I have written the following FlatFileItemWriter to get the properties from School object.

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);
        }
    };
}

Currently the file I am sending out has schoolName, schoolAddress. But I want to get all the properties from subclasses along wth school object in BeanWrapperFieldExtractor. The final output file that I will be sending out should have schoolName, schoolAddress, className, totalCountStudents, sectionName, totalSubjects.

I am not sure on how to do that. Any help would be appreciated. Thanks in advance!


Solution

  • The BeanWrapperFieldExtractor supports the dotted notation for nested properties, so you can define your schoolFieldExtractor as follow:

    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);
            }
        };
    }