compliant validation service provider. If you created the simple Spring JPA utility project in Chapter 10,
the dependency on Hibernate Validator was already added for you.
Spring provides seamless support for the Bean Validation API. The main features include support
for JSR-303 standard annotations for defining validation constraints, custom validators, and
configuration of JSR-303 validation within Spring's ApplicationContext. Let's go through them one by
one in the following sections.
Defining Validation Constraints on Object Properties
Let's begin with applying validation constraints to domain object properties. Listing 14-19 shows a
Customer class with validation constraints applied to the firstName and customerType attributes.
Listing 14-19. The Customer Class
package com.apress.prospring3.ch14.domain;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class Customer {
@NotNull
@Size(min=2, max=60)
private String firstName;
private String lastName;
@NotNull
private CustomerType customerType;
private Gender gender;
// Getter/setter methods omitted
public boolean isIndividualCustomer() {
return this.customerType.equals(CustomerType.INDIVIDUAL);
}
}
In Listing 14-19, the validation constraints applied are shown in bold. For the firstName attribute,
two constraints are applied. The first one is governed by the @NotNull annotation, which indicates that
the value should not be null. Moreover, the @Size annotation governs the length of the firstName
attribute. The @NotNull constraint is applied to the customerType attribute too. Listings 14-20 and 14-21
show the CustomerType and Gender classes, respectively.
Listing 14-20. The CustomerType Class
package com.apress.prospring3.ch14.domain;
public enum CustomerType {
INDIVIDUAL("I"), CORPORATE("C");
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home