Bean Validation: Integrating JSR-303 with Spring

by Uri BonessAugust 4, 2009

I recently had a chance to actually use the new Bean Validation spec. in one of my projects. As the developer of the Bean Validation Framework for Spring (part of the springmodules project) it of course feels a bit weird to ditch all the work I’ve done, but at the same time, it also feels good to use a standard spec that very soon will be finalized. As a member of the JSR-303 expert group (although quite a quiet member) I can assure you that the guys (special kudo’s to Emmanuel Bernard) worked really hard to come up with a specification that will fit in many of the different programming models and technologies we all use (e.g. JPA, JSF, Swing, etc..). In this writing, I’d like to show you a how you can integrate Bean Validation in your Spring based application, especially  if you’re using Spring MVC. Please note, that Spring 3.0 promises to bring such support out of the box, but the last time I checked, it wasn’t implemented yet, and besides, if you’re using Spring 2.x you may find this useful as well.

JSR-303

JSR-303 is a specification for Bean Validation. The work on it started around one and a half years ago as an attempt to come up with a standard declarative validation framework. With Java 5 release and the introduction of annotations, more and more framework developers realized the potential of declarative validation. WebWork had it, Hiberante came up with the Hibernate Validator framework, and I developed such support for spring. We all had the same idea’s, we all shared the same points of views and it was just a matter of time until this would be standardized.

The goal of this specification is not to provide one solution to fit all your validation needs – not at all. There are many types of constraints in an application that span different layers. Data constraints on the database level, business rules on the service level, and even UI constraints purely on the UI level. JSR-303 target what I like to refer to as the model constraints. The idea is very simple – some constraints on your model are tightly coupled to it and therefore belongs next to it. The infrastructure defined by JSR-303 enables you to do that – you can describe the constraints using constraint annotations on your model and validate your model using constraint validators.

As in most cases, an example works best, so let’s look at one. Consider having a class representing an email message with the following constraints:

  • The from property should not be empty and represent an email
  • The to property should not be empty and represent an email
  • The subject is not empty
  • The body is not empty

Here is how you can model it as a java bean and define these constraints:

<br>
public class Email {</p>
<p>    @NotEmpty @Pattern(".+@.+\\.[a-z]+")<br>
    private String from;</p>
<p>    @NotEmpty @Pattern(".+@.+\\.[a-z]+")<br>
    private String to;</p>
<p>    @NotEmpty<br>
    private String subject;</p>
<p>    @NotEmpty<br>
    private String body;</p>
<p>    // setters and getters<br>
    ...<br>
}<br>

NOTE: it is possible to put the annotations on the fields or on the setter methods of the bean properties. Personally I like putting them on the fields as it’s easier to pick up when reading the code.

Here’s the code that actually validates an email object based on these constraints:

<br>
Email email = new Email();<br>
email.setFrom("john@domain.com");<br>
email.setTo("someone");<br>
email.setSubject("");<br>
email.setBody(null);</p>
<p>ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();<br>
Validator validator = validatorFactory.getValidator();</p>
<p>Set<constraintviolation<email>> violations = validator.validate(email);<br>
for (ConstraintViolation<email> violation : violations) {<br>
    String propertyPath = constraintViolation.getPropertyPath().toString();<br>
    String message = constraintViolation.getMessage();<br>
    System.out.println("invalid value for: '" + propertyPath + "': " + message);<br>
}<br>
</constraintviolation

In lines 1-5 we construct the email object and initialize it with invalid data (the to property does not represent a valid email, the subject is empty and the body is null). In lines 7-8 the Validator is created using the default ValidatorFactory. And finally, in lines 10-15, we perform the validation and iterate over the constraint violations that the validator generated.

Spring Validation

Spring has its own mechanism to do validation. It is not declarative but very flexible and extensible. It is mostly used in SpringMVC to preform validation of command object that are bound to request parameters before they are sent to the controllers. In spring the main validation construct is the Validator interface:

&lt;br&gt;
public class Validator {&lt;/p&gt;
&lt;p&gt;    boolean supports(Class type);&lt;/p&gt;
&lt;p&gt;    void validate(Object target, Errors errors);&lt;/p&gt;
&lt;p&gt;}&lt;br&gt;

The supports method indicates whether the validator can validate a specific class. If so, the validate method can be called to validate an instance of that class. The implementation of this method can then register any validation errors that it encounters with the passed in Errors instance.

Although spring doesn’t come with any default implementation of this interface, it does comes with the ValidationUtils class which provides a few helper methods to perform some common validations. Here is the same example as above, but this time the validation is done using a Spring Validator:

&lt;br&gt;
public class EmailValidator implements Validator {&lt;/p&gt;
&lt;p&gt;    private final static Pattern EMAIL_PATTERN = Pattern.compile(&quot;.+@.+\\.[a-z]+&quot;);&lt;/p&gt;
&lt;p&gt;    public boolean supports(Class type) {&lt;br&gt;
        return Email.class.equals(type);&lt;br&gt;
    }&lt;/p&gt;
&lt;p&gt;    public void validate(Object target, Errors errors) {&lt;br&gt;
        Email email = (Email) target;&lt;/p&gt;
&lt;p&gt;        String from = email.getFrom();&lt;br&gt;
        if (!StringUtils.hasText(from)) {&lt;br&gt;
            errors.rejectValue(&quot;from&quot;, &quot;required&quot;);&lt;br&gt;
        } else if (!isEmail(from)) {&lt;br&gt;
            errors.rejectValue(&quot;from&quot;, &quot;invalid.email&quot;);&lt;br&gt;
        }&lt;/p&gt;
&lt;p&gt;        String to = email.getTo();&lt;br&gt;
        if (!StringUtils.hasText(to)) {&lt;br&gt;
            errors.rejectValue(&quot;from&quot;, &quot;required&quot;);&lt;br&gt;
        } else if (!isEmail(to)) {&lt;br&gt;
            errors.rejectValue(&quot;from&quot;, &quot;invalid.email&quot;);&lt;br&gt;
        }&lt;/p&gt;
&lt;p&gt;        ValidationUtils.rejectIfEmpty(errors, &quot;subject&quot;, &quot;required&quot;);&lt;br&gt;
        ValidationUtils.rejectIfEmpty(errors, &quot;body&quot;, &quot;required&quot;);&lt;br&gt;
    }&lt;/p&gt;
&lt;p&gt;    private boolean isEmail(String value) {&lt;br&gt;
        return EMAIL_PATTERN.matcher(value).matches();&lt;br&gt;
    }&lt;br&gt;
}&lt;br&gt;

Now that we’ve defined the validator, we can perform the validation as follows:

&lt;br&gt;
Email email = new Email();&lt;br&gt;
email.setFrom(&quot;john@domain.com&quot;);&lt;br&gt;
email.setTo(&quot;someone&quot;);&lt;br&gt;
email.setSubject(&quot;&quot;);&lt;br&gt;
email.setBody(null);&lt;/p&gt;
&lt;p&gt;BindException errors = new BindException(&quot;email&quot;, email);&lt;br&gt;
EmailValidator validator = new EmailValidator();&lt;br&gt;
validator.validate(email, errors);&lt;/p&gt;
&lt;p&gt;for (FieldError error : (List&lt;fielderror&gt;) errors.getFieldErrors()) {&lt;br&gt;
    System.out.println(&quot;invalid value for: '&quot; + error.getField() + &quot;': &quot; + error.getDefaultMessage());&lt;br&gt;
}&lt;br&gt;

Enjoy both worlds

As you can see, declarative validation is much more elegant, expressive, and in general simpler to use when compared to the classic Spring valiator way. On the other hand, the spring validation mechanism is well integrated in Spring MVC and if you’re using it for your web development, you probably want to take advantage of that. So what we’re really looking for is a way to enjoy both worlds. Luckily, due to the extensible nature of the Spring validation mechanism, we can easily get there. The idea is to simply create a spring validator implementation which delegates the validation tasks to the JSR-303 validator. So let’s do that:

First you’ll need to get a hold of the latest version of the reference implementation for JSR-303. You can either download the following jars manually:

http://repository.jboss.com/maven2/javax/validation/validation-api/1.0.CR3/validation-api-1.0.CR3.jar

http://repository.jboss.com/maven2/org/hibernate/hibernate-validator/4.0.0.Beta2/hibernate-validator-4.0.0.Beta2.jar

Or, if you’re using maven (like me) you can just add the following to your pom:

&lt;br&gt;
&lt;repositories&gt;&lt;br&gt;
    &lt;repository&gt;&lt;br&gt;
        &lt;id&gt;jboss&lt;/id&gt;&lt;br&gt;
        &lt;url&gt;http://repository.jboss.com/maven2&lt;/url&gt;&lt;br&gt;
        &lt;releases&gt;&lt;br&gt;
            &lt;enabled&gt;true&lt;/enabled&gt;&lt;br&gt;
        &lt;/releases&gt;&lt;br&gt;
        &lt;snapshots&gt;&lt;br&gt;
            &lt;enabled&gt;false&lt;/enabled&gt;&lt;br&gt;
        &lt;/snapshots&gt;&lt;br&gt;
    &lt;/repository&gt;&lt;br&gt;
&lt;/repositories&gt;&lt;/p&gt;
&lt;p&gt;&lt;dependencies&gt;&lt;br&gt;
    &lt;dependency&gt;&lt;br&gt;
        &lt;groupid&gt;org.hibernate&lt;/groupid&gt;&lt;br&gt;
        &lt;artifactid&gt;hibernate-validator&lt;/artifactid&gt;&lt;br&gt;
        &lt;version&gt;4.0.0.Beta2&lt;/version&gt;&lt;br&gt;
    &lt;/dependency&gt;&lt;br&gt;
&lt;/dependencies&gt;&lt;br&gt;

Assuming you have your project setup already and spring configured, let’s look at the BeanValidator implementation:

&lt;br&gt;
public class BeanValidator implements org.springframework.validation.Validator, InitializingBean {&lt;/p&gt;
&lt;p&gt;    private Validator validator;&lt;/p&gt;
&lt;p&gt;    public void afterPropertiesSet() throws Exception {&lt;br&gt;
        ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();&lt;br&gt;
        validator = validatorFactory.usingContext().getValidator();&lt;br&gt;
    }&lt;/p&gt;
&lt;p&gt;    public boolean supports(Class clazz) {&lt;br&gt;
        return true;&lt;br&gt;
    }&lt;/p&gt;
&lt;p&gt;    public void validate(Object target, Errors errors) {&lt;br&gt;
        Set&lt;constraintviolation&lt;object&gt;&amp;gt; constraintViolations = validator.validate(target);&lt;br&gt;
        for (ConstraintViolation&lt;object&gt; constraintViolation : constraintViolations) {&lt;br&gt;
            String propertyPath = constraintViolation.getPropertyPath().toString();&lt;br&gt;
            String message = constraintViolation.getMessage();&lt;br&gt;
            errors.rejectValue(propertyPath, &quot;&quot;, message);&lt;br&gt;
        }&lt;br&gt;
    }&lt;br&gt;
}&lt;br&gt;

Since the validation framework can potentially validate any object, the supports method return true to all types. Also notice that the bean validator is actually created at load time. This is fine as according to the spec. a Validator instance must be thread safe – this means that we can register this BeanValidator as a singleton in the application context and reuse it in all our controllers. All the validate method does is translate the constraint violations to error messages which are registered with the passed in errors instance.

Now that we have the BeanValidator ready, all that is required in order to use it is to register it in the application context. If you’re using spring’s component-scaning mechanism, you can simply annotate it with the @Component annotation, otherwise you can just add the following line to your application context configuration:

&lt;br&gt;
&lt;bean id=&quot;beanValidator&quot; class=&quot;package.name.BeanValidator&quot;&gt;&lt;br&gt;

Done! You can now inject this validator to all your SpringMVC controllers and benefit from the JSR-303 declarative validation.

Writing you own custom constraints

JSR-303 defines a set of constraints that should be supported out of the box by all providers. But this is a relatively limited set and when developing real world application you’ll probably find the need to extend it and provide your own custom constraints. There are two ways of doing this – write it from scratch or combine a constraints from other already existing constraints.

Writing from scratch

To write a new constraint from scratch you first need to know how JSR-303 constraints work.

A constraint is basically a pair of an annotation and its associated validator class. When a bean is validated, it is being scanned for all the constraint annotations. Once such annotation is found its associated validator is created and initialized with the annotation (the annotation in a way serves as the configuration for its validator). How does the framework know which validator to instantiate? well… the annotation indicates it, and it’s best explained by an example.

In the first example above, we showed how one can validate an email using the @Pattern annotation. It would be much more expressive (and semantically right) if we would have an @Email annotation instead which would also relieve us from remembering the email regular expression each time we need to apply this constraint. To make it work we’ll first define the @Email annotation:

&lt;br&gt;
@Documented&lt;br&gt;
@Constraint(validatedBy = EmailValidator.class)&lt;br&gt;
@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE })&lt;br&gt;
@Retention(RetentionPolicy.RUNTIME)&lt;br&gt;
public @interface Email {&lt;/p&gt;
&lt;p&gt;    public abstract String message() default &quot;{package.name.Email.message}&quot;;&lt;/p&gt;
&lt;p&gt;    public abstract Class&lt;!--?--&gt;[] groups() default {};&lt;/p&gt;
&lt;p&gt;    public abstract Class&lt;!--? extends ConstraintPayload--&gt;[] payload() default {};&lt;/p&gt;
&lt;p&gt;}&lt;br&gt;

All the defined attributes in this annotation are specified in the spec. and mandatory for all constraint annotations. I will not discuss the payload and groups attributes but the message attribute defines the error message that should be used in case the constraint is violated. Beside these mandatory attributes, each constraint annotation can define additional attributes as needed. In our example, there no such need, but a @Range annotation for example, which can be used to define the boundaries of an integer value, will probably define a min and a max attributes.

NOTE: The specification define quite a powerful message interpolation mechanism for the error messages. The message can contain placeholders (surrounded by curly brackets) which can be replaced by the attributes defined in the annotation itself. Furthermore, the placeholders can also refer to keys defined in a resource bundle. In the later case the placeholders will be replaced by their associated values in the bundle. For example, as we did in the @Email annotation, it is considered a best practice to assign a default message value. This value actually consists of one parameter placeholder which refers to a key in a resource bundle (“package.name.Email.message“). When the error message is resolved, the value of this key is looked up in the resource bundle and when found replaces the placeholder. By default, the validator will look for a resource bundle named ValidationMessages.properties in the classpath.

Notice that the @Email annotation itself is annotated with a @Constraint annotation. This annotation indicates that @Email is a constraint. The validatedBy attributes indicates the validator class which should be used to validate the constraint. This is how the bean validator knows which constraint validator class to instantiate. Let’s look at the EmailValidator class:

&lt;br&gt;
public class EmailValidator implements ConstraintValidator&lt;email, string=&quot;&quot;&gt; {&lt;/email,&gt;&lt;/p&gt;
&lt;p&gt;    private final static Pattern EMAIL_PATTERN = Pattern.compile(&quot;.+@.+\\.[a-z]+&quot;);&lt;/p&gt;
&lt;p&gt;    public void initialize(Email constraintAnnotation) {&lt;br&gt;
        // nothing to initialize&lt;br&gt;
    }&lt;/p&gt;
&lt;p&gt;    public boolean isValid(String value, ConstraintValidatorContext context) {&lt;br&gt;
        return EMAIL_PATTERN.matcher(value).matches();&lt;br&gt;
    }&lt;br&gt;
}&lt;br&gt;

The first thing to note about this class is that it implements the ConstraintValidator interface. This interface accepts two generic types – the first indicates the annotation it is associated with (@Email in our case) and the second indicates the type of objects it can validate (String in our case).

The initialize method (line 5) is called after the constraint validator is instantiated. The constraint annotation is passed in as the configuration. Continuing the @Range example from above, a RangeValidator will probably extract the min and max values from the annotation which will later be used to perform the actual range validation.

The isValid method (line 9) does the actual validation. This is where you need to put the validation logic, which in our case, is just matching the string to an email regular expression.

The only thing that is left to do, is to create a ValidationMessage.properties file and put it in the classpath. This is the user defined resource bundle that the bean validator work with by default. Now, add the default error message code to it to provide a default user friendly message:

&lt;br&gt;
package.name.Email.message=Invalid email&lt;br&gt;

Thats it, you’re done. You can change the original code of our email example to use this new annotation (instead of the @Pattern annotation) and see it in action.

Composing annotations

Sometimes there is no real need to create constraint entirely from scratch. It is often the case where a constraint is either a specific variation of another constraint, or a combination of other finer grained constraints. The specification acknowledges that and makes it even easier to define such constraints.

Take the @Email constraint for example. Instead of creating a validator for it, we can also view this constraint as a narrowed version (or a specific case) of the @Pattern constraint. So we can actually compose it instead of creating from scratch.

In order to compose an annotation, all that is needed is to annotate the new constraint annotation with the constraint annotations that compose it. hmmm… confuse? well, an example will clear it up. Here is the @Email annotation again, yet this time it is composed of the standard @Pattern annotation:

&lt;br&gt;
@Documented&lt;br&gt;
@Constraint(validatedBy = {})&lt;br&gt;
@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE })&lt;br&gt;
@Retention(RetentionPolicy.RUNTIME)&lt;br&gt;
@Pattern(regexp = &quot;.+@.+\\.[a-z]+&quot;)&lt;br&gt;
@ReportAsSingleViolation&lt;br&gt;
public @interface Email {&lt;/p&gt;
&lt;p&gt;    public abstract String message() default &quot;{package.name.Email.message}&quot;;&lt;/p&gt;
&lt;p&gt;    public abstract Class&lt;!--?--&gt;[] groups() default {};&lt;/p&gt;
&lt;p&gt;    public abstract Class&lt;!--? extends ConstraintPayload--&gt;[] payload() default {};&lt;/p&gt;
&lt;p&gt;}&lt;br&gt;

As you can see, no validator is associated with this annotation. Instead, it is annotated with the @Pattern annotation which holds the email regular expression. By default, when the validation is performed, all the composing constraints are evaluated (in our case, the @Patterm constraint) and register any encountered violations. It is sometimes (if not often) the case where you’d like only one error message to be reported – in our case, an “invalid email” message (not a “pattern mismatch” message). This is where the @ReportAsSingleViolation annotation becomes useful. This annotation indicates that on any constraint violation of any of the composing constraints, only one violation will be reported and it is of the composed constraint – all the other reported violations of the composing annotations will then be ignored.

Loading constraint validators from spring

As you’ve seen, the default implementation of the Validator instantiates the ConstraintValidators via reflection. Although good enough for most cases, sometimes the validation logic requires interaction with external services (for example, finding out whether a username is unique in the system). If you have this requirement and you’re using spring, you probably want these services to be injected into the validator, and in fact, let spring instantiate the validator all together. To achieve that you’ll need to modify the BeanValidator implementation a bit:

&lt;br&gt;
public class BeanValidator implements org.springframework.validation.Validator,&lt;br&gt;
        InitializingBean, ApplicationContextAware, ConstraintValidatorFactory {&lt;/p&gt;
&lt;p&gt;    private Validator validator;&lt;/p&gt;
&lt;p&gt;    private ApplicationContext applicationContext;&lt;/p&gt;
&lt;p&gt;    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {&lt;br&gt;
        this.applicationContext = applicationContext;&lt;br&gt;
    }&lt;/p&gt;
&lt;p&gt;    public void afterPropertiesSet() throws Exception {&lt;br&gt;
        ValidatorFactory validatorFactory = Validation.byDefaultProvider().configure()&lt;br&gt;
                .constraintValidatorFactory(this).buildValidatorFactory();&lt;br&gt;
        validator = validatorFactory.usingContext().getValidator();&lt;br&gt;
    }&lt;/p&gt;
&lt;p&gt;    public &lt;t extends=&quot;&quot; constraintvalidator&lt;?,=&quot;&quot; ?=&quot;&quot;&gt;&amp;gt; T getInstance(Class&lt;t&gt; key) {&lt;/t&gt;&lt;/t&gt;&lt;/p&gt;
&lt;p&gt;        Map beansByNames = applicationContext.getBeansOfType(key);&lt;br&gt;
        if (beansByNames.isEmpty()) {&lt;br&gt;
            try {&lt;br&gt;
                return key.newInstance();&lt;br&gt;
            } catch (InstantiationException e) {&lt;br&gt;
                throw new RuntimeException(&quot;Could not instantiate constraint validator class '&quot; + key.getName() + &quot;'&quot;, e);&lt;br&gt;
            } catch (IllegalAccessException e) {&lt;br&gt;
                throw new RuntimeException(&quot;Could not instantiate constraint validator class '&quot; + key.getName() + &quot;'&quot;, e);&lt;br&gt;
            }&lt;br&gt;
        }&lt;br&gt;
        if (beansByNames.size() &amp;gt; 1) {&lt;br&gt;
            throw new RuntimeException(&quot;Only one bean of type '&quot; + key.getName() + &quot;' is allowed in the application context&quot;);&lt;br&gt;
        }&lt;br&gt;
        return (T) beansByNames.values().iterator().next();&lt;br&gt;
    }&lt;/p&gt;
&lt;p&gt;    public boolean supports(Class clazz) {&lt;br&gt;
        return true;&lt;br&gt;
    }&lt;/p&gt;
&lt;p&gt;    public void validate(Object target, Errors errors) {&lt;br&gt;
        Set&lt;constraintviolation&lt;object&gt;&amp;gt; constraintViolations = validator.validate(target);&lt;br&gt;
        for (ConstraintViolation&lt;object&gt; constraintViolation : constraintViolations) {&lt;br&gt;
            String propertyPath = constraintViolation.getPropertyPath().toString();&lt;br&gt;
            String message = constraintViolation.getMessage();&lt;br&gt;
            errors.rejectValue(propertyPath, &quot;&quot;, message);&lt;br&gt;
        }&lt;br&gt;
    }&lt;br&gt;

As you can see, out BeanValidator now implements two additional interfaces. The first is Spring’s ApplicationContextAware interface. This will cause the application context to be injected into the validator. The second interface is the ConstraintValidationFactory. It is a JSR-303 interface which abstract the way the constraint validators are constructed. In our case, we first try to find a bean in the application context that matches the type of the constraint (lines 20-29). If none is found, we just instantiate the constraint class using reflection. Otherwise, we make sure that there’s only one bean definition of the constraint class and if so, it is returned (lines 30-33). The last change we needed to make in order for it to work is to configure the validator factory to use the new constraint validator factory. You can see how this is done at lines 13-14. Now, if your constraint validator requires other services, just add it to the application context, configure its dependencies and you’re done.

Conclusion

Well, that’s it for this entry. I tried to introduce you to the new JSR-303 bean validation specification and show you how you can already work and integrate with your spring applications. You have to remember though, that this spec is still undergoing some last changes and is not final yet (though personally, I don’t expect to see any major changes in the final version).

For me, although it’s not final yet and although the reference implementation is still in beta, I already feel comfortable using it in a real world project. Yes, there might be some bugs (they are fixed pretty quickly once reported), and I might need to change a few little things when the final release is out, but at the same time, I benefit from cleaner code that confirms to the standards and it always makes me happy when my projects are up to date with the latest and greatest technologies out there.

</constraintviolation

</constraintviolation