Java Reference
In-Depth Information
<beans:property name="delegate" ref="xmlOutputWriter"/>
<beans:property name="itemCountLimitPerResource" value="10"/>
<beans:property name="resourceSuffixCreator" ref="customerSuffixCreator"/>
</beans:bean>
By running the job again with the additional configuration provided in Listing 9-67, you get a
slightly different result, as shown in Listing 9-68.
Listing 9-68. Results Using ResourceSuffixCreator
michael-minellas-macbook-pro:output mminella$ ls /output/
custOutputs1.xml custOutputs2.xml custOutputs4.xml custOutputs6.xml
custOutputs8.xml
custOutputs10.xml custOutputs3.xml custOutputs5.xml custOutputs7.xml
custOutputs9.xml
You surely agree that the file names in Listing 9-68 are more like what you would expect when
generating XML files.
Header and Footer XML Fragments
When creating files, whether a single file for a step/job or multiple files as you saw in the previous
example, it's common to need to be able to generate a header or footer on the file. You can use a header
to define the format of a flat file (what fields exist in a file or in what order) or include a separate, non-
item-related section in an XML file. A footer may include the number of records processed in the file or
totals to use as integrity checks after a file has been processed. This section looks at how to generate
header and footer records using Spring Batch's callbacks available for them.
When opening or closing a file, Spring Batch provides the ability to add either a header or footer
(whichever is appropriate) to your file. Adding a header or footer to a file means different things based
on whether it's a flat file or an XML file. For a flat file, adding a header means adding one or more
records to the top or bottom of the file. For an XML file, you may want to add an XML segment at either
the top or bottom of the file. Because the generation of plain text for a flat file is different from
generating an XML segment for an XML file, Spring Batch offers two different interfaces to implement
and make this happen. Let's begin by looking at the XML callback interface,
org.springframework.batch.item.xml.StaxWriterCallback .
The StaxWriterCallback interface consists of a single write method that is used to add XML to the
current XML document. Spring Batch executes a configured callback once at either the header or footer
of the file (based on the configuration). To see how this works, in this example you write a
StaxWriterCallback implementation that adds an XML fragment containing the name of the person who
wrote the job (me). Listing 9-69 shows the code for the implementation.
Listing 9-69. CustomerXmlHeaderCallback
package com.apress.springbatch.chapter9;
import java.io.IOException;
import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLEventWriter;
 
 
Search WWH ::




Custom Search