Java Reference
In-Depth Information
Validate input : In the original version of Spring Batch, validation occurred at the
ItemReader by subclassing the ValidatingItemReader class. The issue with this
approach is that none of the provided readers subclassed the
ValidatingItemReader class so if you wanted validation, you couldn't use any of
the included readers. Moving the validation step to the ItemProcessor allows
validation to occur on an object before processing, regardless of the input method.
This makes much more sense from a division-of-concerns perspective.
Reuse existing services : Just like the ItemReaderAdapter you looked at in Chapter 7
to reuse services for your input, Spring Batch provides an ItemProcessorAdapter
for the same reason.
Chain ItemProcessors : There are situations where you will want to perform
multiple actions on a single item within the same transaction. Although you could
write your own custom ItemProcessor to do all of the logic in a single class, that
couples your logic to the framework, which is something you want to avoid.
Instead, Spring Batch allows you to create a list of ItemProcessors that will be
executed in order against each item.
To accomplish this, the org.springframework.batch.item.ItemProcessor interface consists of a
single method process shown in Listing 8-1. It takes an item as read from your ItemReader and returns
another item.
Listing 8-1. ItemProcessor Interface
package org.springframework.batch.item;
public interface ItemProcessor<I, O> {
O process(I item) throws Exception;
It's important to note that the type the ItemProcessor receives as input does not need to be the
same type it returns. The framework allows for you to read in one type of object and pass it to an
ItemProcessor and have the ItemProcessor return a different type for writing. With this feature, you
should note that the type the final ItemProcessor returns is required to be the type the ItemWriter takes
as input. You should also be aware that if an ItemProcessor returns null, all processing of the item will
stop. In other words, any further ItemProcessors for that item will not be called nor shall the ItemWriter
for the step. However, unlike returning null from an ItemReader, which indicates to Spring Batch that all
input has been exhausted, processing of other items will continue when an ItemProcessor returns null.
Note The type an ItemProcessor returns doesn't need to be the same as it takes in as input.
Let's take a look at how to use ItemProcessors for your jobs. To start, you'll dig into the ones
provided by the framework.
Search WWH ::

Custom Search