Pivotal Knowledge Base

Follow

Integrating JSR-303 Bean Validation into Spring Framework Applications

Environment

 Product  Version
 Spring Framework  3.0 and above

Overview

Bean Validation API (JSR-303) is a standard for validation constraint declaration and metadata for the Java platform. This API allows you to annotate domain model properties with declarative validation constraints which are enforced by the runtime. You may take advantage of the built-in constraints, or define your own custom constraints.

Description

Spring Framework 3.0 and above fully support the Bean Validation API. Apart from the default validation of the domain model entities, developers can leverage from an enhanced DataBinder support for programmatical bean validation, or from declarative validation of @Controller inputs within Spring MVC applications.

Injecting JSR-303 Validator for Programmatical Use

To configure a bean validation implementation within Spring application, you must define a bean of type org.springframework.validation.beanvalidation.LocalValidatorFactoryBean as such:

<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/> 

This basic configuration above will trigger the Bean Validation API to initialize using its default bootstrap mechanism. A JSR-303 provider (such as Hibernate Validator) is expected to be present on the classpath and will be detected automatically. As this factory bean implements both javax.validation.ValidatorFactory, javax.validation.Validator, as well as org.springframework.validation.Validator, you can inject a reference to either of these interfaces into beans which requires invoking some validation logic.

Configuring JSR-303 Enabled DataBinder

A Spring Framework 3.0 org.springframework.validation.DataBinder instance can be configured with a bean validator. Once configured, validation logic can be invoked by calling binder.validate(). Validation errors are automatically added to the binder's org.springframework.validation.BindingResult and can be retrieved by calling binder.getBindingResult():

// Inject or instantiate a JSR-303 validator
Validator validator;
Foo target = new Foo();
DataBinder binder = new DataBinder(target);
binder.setValidator(validator);
// bind to the target object
binder.bind(propertyValues);
// validate the target object
binder.validate();
// get BindingResult that includes any validation errors
BindingResult results = binder.getBindingResult();

Configuring a JSR-303 Validator for Use by Spring MVC

To configure a JSR-303 Validator for use by Spring MVC, drop a JSR-303 provider (such as Hibernate Validator) to the application classpath, enable MVC annotation-driven configuration. Spring MVC detects and bootstraps a JSR-303 validator automatically:

<xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

  xmlns:mvc="http://www.springframework.org/schema/mvc"

  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  xsi:schemaLocation="

      http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

      http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

  <!-- JSR-303 support will be detected on classpath and enabled automatically -->

  <mvc:annotation-driven/>

</beans>

Use javax.validation.Valid annotation to trigger validation by JSR-303 provider. Any detected javax.validation.ConstraintViolations is automatically exposed as errors in the BindingResult instance and can be rendered by standard Spring MVC form tags:

@Controller
public class FooController {
   @RequestMapping("/foo", method=RequestMethod.POST)
   public void processFoo(@Valid Foo foo, BindingResult errors) {
       if (errors.hasErrors()) {
           // posted foo instance is not valid and should be resubmitted
       } else {
        // posted foo instance is valid and can be processed
     }
  }
}

 

Comments

Powered by Zendesk