Tuesday, April 27, 2010

Spring Batch - ItemReader and ItemWriter configuration

How to read a record to a object
ItemReader will utilize LineMapper, LineTokenizer and FieldSetMapper to get a Object.
LineMapper: DefaultLineMapper, PattermMatchingCompositeLineMapper
LineTokenizer: DelimitedLineTokenizer, FixedLengthTokenizer, PattermMatchingCompositeLineTokenizer
FieldSetMapper: BeanWrapperFieldSetMapper
Configuration Hierarchy:
<ItemReader>
  <LineMapper>
    <LineTokenizer/>
    <FieldMapper/>
  </LineMapper>
<ItemReader/>

Multiple record type with single file

It is very common that a file might have records with different formats that need to be tokenized differently and mapped to different objects.

USER;Smith;Peter;;T;20014539;F
LINEA;1044391041ABC037.49G201XX1383.12H
LINEB;2134776319DEF422.99M005LI

The PatternMatchingCompositeLineMapper makes this easy by allowing maps of patterns to LineTokenizers and patterns to FieldSetMappers to be configured:



<bean id="orderFileLineMapper" class="org.spr...PatternMatchingCompositeLineMapper">
  <property name="tokenizers">
    <map>
      <entry key="USER*" value-ref="userTokenizer" />
      <entry key="LINEA*" value-ref="lineATokenizer" />
      <entry key="LINEB*" value-ref="lineBTokenizer" />
    </map>
  </property>
  <property name="fieldSetMappers">
    <map>
      <entry key="USER*" value-ref="userFieldSetMapper" />
      <entry key="LINE*" value-ref="lineFieldSetMapper" />
    </map>
  </property>
</bean>


How to write a file
The ItemWriter will leverage the LineAggregator and FieldExtractor to write out the data to file.
LineAggregator: PassThroughLineAggregator, DelimitedLineAggregator
FieldExtractor: BeanWrapperFieldExtractor


Configuration Hierarchy:
<ItemWriter>
  <LineAggregator>
    <FieldExtractor/>
  </LineAggregator>
<ItemWriter/>