Currently, I have this method implemented for five different class to configure FlatFileReader for five different text files and load into DB table.
I would like to know is there a way to implement this method in a common place So that my each file will call this method to configure my reader to read their corresponding files..
Every file will send different entity class to load their file. like Primary Entity, ChildEntity1, ChildEntity2, ChildEntity3, ChildEntity4.
private void flatFileItemReaderConfig(FlatFileItemReader<PrimaryEntity> flatFileReader, String fileName, String incomingHeader) { // set delimiter as '|' DefaultLineMapper<PrimaryEntity> defaultLineMapper = new DefaultLineMapper<>(); DelimitedLineTokenizer delimitedLineTokenizer = new DelimitedLineTokenizer("|"); delimitedLineTokenizer.setNames(convertHeaderToEntityAttrib(fileName, incomingHeader)); defaultLineMapper.setLineTokenizer(delimitedLineTokenizer); // convert each record into primaryentity BeanWrapperFieldSetMapper<PrimaryEntity> beanWrapperFieldSetMapper = new BeanWrapperFieldSetMapper<>(); beanWrapperFieldSetMapper.setTargetType(PrimaryEntity.class); beanWrapperFieldSetMapper.setCustomEditors(getCustomFormatters()); defaultLineMapper.setFieldSetMapper(beanWrapperFieldSetMapper); flatFileReader.setLineMapper(defaultLineMapper); }
Advertisement
Answer
Add generics to the method
private <T> void flatFileItemReaderConfig(FlatFileItemReader<T> flatFileReader, String fileName, String incomingHeader, Class<T> clazz) { // set delimiter as '|' DefaultLineMapper<T> defaultLineMapper = new DefaultLineMapper<>(); DelimitedLineTokenizer delimitedLineTokenizer = new DelimitedLineTokenizer("|"); delimitedLineTokenizer.setNames(convertHeaderToEntityAttrib(fileName, incomingHeader)); defaultLineMapper.setLineTokenizer(delimitedLineTokenizer); // convert each record into primary entity BeanWrapperFieldSetMapper<T> beanWrapperFieldSetMapper = new BeanWrapperFieldSetMapper<>(); beanWrapperFieldSetMapper.setTargetType(clazz); beanWrapperFieldSetMapper.setCustomEditors(getCustomFormatters()); defaultLineMapper.setFieldSetMapper(beanWrapperFieldSetMapper); flatFileReader.setLineMapper(defaultLineMapper); }
If you want to limit the usage only to the listed entities, create a common interface Entity that is implemented by all concrete entities (PrimaryEntity, ChildEntity1, ChildEntity2, ChildEntity3, ChildEntity4
) and change the signature to
private <T extends Entity> void flatFileItemReaderConfig(...)