Java Reference
In-Depth Information
Introduction to ItemWriters
The ItemWriter is the output mechanism used in Spring Batch. When Spring Batch first came out,
ItemWriters were essentially the same as ItemReaders. They wrote each item out as it was processed.
However, with Spring Batch 2 and the introduction of chunk-based processing, the role of the
ItemWriter changed. Writing out each item as it's processed no longer makes sense.
With chunked-based processing, an ItemWriter doesn't write a single item: it writes a chunk of
items. Because of this, the org.springframework.batch.item.ItemWriter interface is slightly different
than the ItemReader interface. Listing 9-1 shows that the ItemWriter's write method takes a list of items,
whereas the ItemReader interface you looked at in Chapter 7 returns only a single item from the read
Listing 9-1. ItemWriter
package org.springframework.batch.item;
import java.util.List;
public interface ItemWriter<T> {
void write(List<? extends T> items) throws Exception;
To illustrate the flow of how an ItemWriter fits into the step, Figure 9-1 shows a sequence diagram
that walks through the processing within a step. The step reads each item individually via the
ItemReader and passes it to the ItemProcessor for processing. This interaction continues until the
number of items in a chunk has been processed. With the processing of a chunk complete, the items are
passed into the ItemWriter to be written accordingly.
For each item
Figure 9-1. Step interaction with an ItemWriter
Since chunk-based processing was introduced, the number of calls to an ItemWriter is much less
than it was. However, you need to handle things a bit differently. Take for example working with
nontransactional resources like files. If a write to a file fails, there is no way to roll back what was already
written. Because of that, if you write a custom writer, you should buffer the output and flush all at once
to the file to prevent an item from being half written, leaving the file in an inconsistent state.
Spring Batch provides a number of writers to handle the vast majority of output scenarios. Let's start
with writers at the same place you started with readers: FlatFileItemWriter .
Search WWH ::

Custom Search