Java Reference
In-Depth Information
private String middleInitial;
@NotNull
@Pattern(regexp="[a-zA-Z]+")
private String lastName;
@NotNull
@Pattern(regexp="[0-9a-zA-Z\\. ]+")
private String address;
@NotNull
@Pattern(regexp="[a-zA-Z\\. ]+")
private String city;
@NotNull
@Size(min=2,max=2)
@Pattern(regexp="[A-Z]{2}")
private String state;
@NotNull
@Size(min=5,max=5)
@Pattern(regexp="\\d{5}")
private String zip;
// Accessors go here
}
A quick look at the rules defined in Listing 8-4 may make you ask why use both the @Size annotation
and the @Pattern one when the regular expression defined in the @Pattern would satisfy both. You are
correct. However, each annotation allows you to specify a unique error message (if you want);
moreover, being able to identify if the field was the wrong size vs. the wrong format may be helpful in the
future.
At this point, you have defined the validation rules you will use for your Customer item. However,
there is no Validator implementation within Spring yet that handles the execution of these rules.
Because of this, you will have to create your own. Fortunately, it only requires a couple lines of code to
create a universal validator for the basic JSR 303 validations. To do this, you will implement Spring
Batch's org.springframework.batch.item.validator.Validator interface and use Hibernate's
implementation of the javax.validation.Validator to validate your item. Listing 8-5 shows the code for
the validator.
Listing 8-5. BeanValidator
package com.apress.springbatch.chapter8;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;
 
Search WWH ::




Custom Search