Java Reference
In-Depth Information
import org.springframework.batch.item.validator.ValidationException;
import org.springframework.batch.item.validator.Validator;
import org.springframework.beans.factory.InitializingBean;
public class BeanValidator implements Validator, InitializingBean {
private javax.validation.Validator validator;
public void afterPropertiesSet() throws Exception {
ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
validator = validatorFactory.usingContext().getValidator();
public void validate(Object target) throws ValidationException {
Set<ConstraintViolation<Object>> constraintViolations = validator.validate(target);
if(constraintViolations.size() > 0) {
private void buildValidationException(
Set<ConstraintViolation<Object>> constraintViolations) {
StringBuilder message = new StringBuilder();
for (ConstraintViolation<Object> constraintViolation : constraintViolations) {
message.append(constraintViolation.getMessage() + "\n");
throw new ValidationException(message.toString());
Implementing Spring Batch's Validator interface as well as Spring's
org.springframework.beans.factory.InitializingBean interface allows you to obtain an instance of the
Java validator in the afterPropertiesSet method and execute the validation within the validate
method. Once you have validated the object, you can construct a ValidationException out of the
messages you received if any attributes failed validation.
Note The Validator interface included in the Spring Batch framework is not the same as the Validator interface
that is part of the core Spring framework. Spring Batch provides an adapter class, SpringValidator , to handle
the differences.
Let's see how all of this works together by creating a job to put them to use. Your job will read a
comma-delimited file into your Customer object, which will then be valided as part of the
Search WWH ::

Custom Search