if (getCustomerType() != null &&
(isIndividualCustomer() && (gender == null || lastName == null)))
result = false;
return result;
}
}
As shown in Listing 14-29, the isValidIndividualCustomer() method is added to the Customer
class and annotated with @AssertTrue (which is under the package javax.validation.constraints).
When invoking validation, the provider will invoke the checking and make sure that the result is true.
JSR-303 also provides the @AssertFalse annotation to check for some condition that should be false.
Now run the testing program (Jsr303Sample) again, and you will get the same output as produced by
the custom validator.
Considerations for Custom Validation
So, for custom validation in JSR-303, which approach should you use? The custom validator or the
@AssertTrue annotation? Generally, the @AssertTrue method is simpler to implement, and you can see
the validation rules right in the code of the domain objects.
However, for validators with more complicated logic (for example, you need to inject a service class,
access a database, and check for some valid values), then implementing a custom validator is the way to
go, because you never want to inject service-layer objects into your domain objects. Also, custom
validators can be reused across similar domain objects.
Which Validation API to Use?
Having discussed Spring's own Validator interface and the Bean Validation API, which one should you
use in your application? JSR-303 is definitely the way to go. The following are the major reasons:
JSR-303 is a JEE standard and is broadly supported by many frontend/backend
·
frameworks (for example, Spring, JPA 2, Spring MVC, GWT, and so on).
JSR-303 provides a standard validation API that hides the underlying provider, so
·
you are not tied to a specific provider.
Spring tightly integrates with JSR-303 starting with version 3. For example, in the
·
Spring MVC web controller, you can annotate the argument in a method with the
@Valid (under the package javax.validation) annotation, and Spring will invoke
JSR-303 validation automatically during the data-binding process. Moreover, in a
Spring MVC web application context configuration, a simple tag called
<mvc:annotation-driven/> will configure Spring to automatically enable the
Spring 3 type conversion system and field formatting, as well as support of JSR-303
Bean Validation.
If you are using JPA 2, the provider will automatically perform JSR-303 validation
·
to the entity before persisting, providing another layer of protection.
For detailed information about using JSR-303 Bean Validation with Hibernate Validator as the
implementation provider, please refer to Hibernate Validator's documentation page
(http://docs.jboss.org/hibernate/validator/4.2/reference/en-US/html).
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home