Java Reference
In-Depth Information
Using Spring Batch's ItemProcessors
When you looked at the ItemReaders previously, there was a lot of ground to cover regarding what was
provided from Spring Batch because input and output are two relatively standard things. Reading from
a file is the same in most cases. Writing to a database works the same with most databases. However,
what you do to each item is different based upon your business requirements. This is really what makes
each job different. Because of this, the framework can only provide you with the facility to either
implement your own or wrap existing logic. This section will cover the ItemProcessors that are included
in the Spring Batch framework.
You'll start your look at Spring Batch's ItemProcessor implementations with where you left off in
Chapter 7. Previously, you handled obtaining input for your jobs; however, just because you can read it
doesn't mean it's valid. Data validation with regards to types and format can occur within an
ItemReader; however, validation via business rules is best left once the item has been constructed.
That's why Spring Batch provides an ItemProcessor implementation for validating input called the
ValidatingItemProcessor. In this section, you will look at how to use it to validate your input.
Input Validation
The org.springframework.batch.item.validator.ValidatingItemProcessor is an implementation of the
ItemProcessor interface that allows you to set an implementation of Spring Batch's Validator interface 1
to be used to validate the incoming item prior to processing. If the item passes validation, it will be
processed. If not, an org.springframework.batch.item.validator.ValidationException is thrown,
causing normal Spring Batch error handling to kick in.
JSR 303 is the Java specification for bean validation. Because it only came out in late 2009, it hasn't
been as widely integrated as I would like; however, I consider it a better alternative to the Spring
Modules 2 examples show in most Spring Batch documentation. The validation performed via the
javax.validation.* code is configured via annotations. There is a collection of annotations that
predefine validation functions out of the box; you also have the ability to create your own validation
functions. Let's start by looking at how you would validate a Customer class like the one in Listing 8-2.
Listing 8-2. Customer Class
package com.apress.springbatch.chapter8;
public class Customer {
private String firstName;
private String middleInitial;
private String lastName;
private String address;
private String city;
1 Although Spring does have a Validator interface of its own, the ValidatingItemProcessor uses one from
Spring Batch instead.
2 The Spring Modules project was retired as of late 2010 in favor of the Spring Extensions project.
Search WWH ::

Custom Search