by Rafał Borowiec

Menu

Monday, March 5, 2012

Spring MVC 3.1 Bean Validation support has been extended with @Validated annotation. The annotation is a Spring's specific variant of JSR-303's javax.validation.Valid, supporting the specification of validation groups. @Validated may be used either with Spring's @Controller method arguments or with with method-level validation.

In order to indicate that a specific class is supposed to be validated at the method level it needs to be annotated with @Validated annotation at type level:

@Service
@Validated
public class UserCreateService {
}

Methods applicable for validation must have JSR-303 constraint annotations on their parameters and/or on their return value:

Beans annotated with @Validated annotation will be detected by MethodValidationPostProcessor and validation functionality is delegetated to Hibernate's MethodValidator that requires Hibernate Validator 4.2 or higher. When the validation fails MethodConstraintViolationException, with a set of contraint violations, is thrown.
The easiest way to understand and verify method-level validation is to create a unit test. The context of the test is configured by very simple @Config class. Expected exceptions are verified with JUnit ExpectedException rule and three custom Hamcrest matchers:

has n contraint violations (HasContraintViolations)

has contraint violation for parameter with index i and message containing m (ParameterViolation)

Within couple of minutes we have learned the basic usage of method-level validation in Spring 3.1. But there is one pending question: "Do we want to utilize method-level validation in production code?". What's your opinion?