Spring Batch - more than one writer based on field value

て烟熏妆下的殇ゞ 提交于 2019-12-31 01:55:09

问题


I am working on spring batch, for writer currently using FlatFileItemWriter.

I would like to write my input file content to more than one flat file based on some field value. Is Spring batch support any kind of functionality by default.[something similar to CompositeItemWriter]

For example, my input file content is something like this.

john,35,retail,10000
joe,34,homeloan,20000
Amy,23,retail,2000

Now i would like to write two different files based on third column, it means row 1 and row 3 should go to file1 and row 2 should go to file2.

My writer configuration is:

<bean id="fileWriter" class="org.springframework.batch.item.file.FlatFileItemWriter">

        <property name="resource" value="file:C:/output.dat"/>

        <property name="lineAggregator">
            <bean class="org.springframework.batch.item.file.transform.DelimitedLineAggregator">
                <property name="delimiter" value="|" />
                <property name="fieldExtractor">
                    <bean class="org.springframework.batch.item.file.transform.BeanWrapperFieldExtractor">
                        <property name="names" value="field1,field2...." />
                    </bean>
                </property>
            </bean>
        </property>
    </bean>

回答1:


Take a look at the ClassifierCompositeItemWriter. This ItemWriter implementation allows you to define a Classifier that chooses which of the defined delegate ItemWriter instances to delegate to. In your case, you'd create a Classifier that decided based on field4 and delegate the writing to the appropriate instance of the FlatFileItemWriter.

You can read more about the ClassifierCompositeItemWriter in the documentation here: http://docs.spring.io/spring-batch/trunk/apidocs/org/springframework/batch/item/support/ClassifierCompositeItemWriter.html




回答2:


Use a ClassifierCompositeItemWriter

Calls one of a collection of ItemWriters for each item, based on a router pattern implemented through the provided Classifier.

Router pattern is based on bean content



来源:https://stackoverflow.com/questions/29520949/spring-batch-more-than-one-writer-based-on-field-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!