Saturday, 2 March 2013

JSR 303 Bean Validation with Spring

I have to work out how to do this far too often, so I'm writing it down. It's actually really easy, but there's always something that catches me out. So here it is.

Firstly, the dependencies. I'm using Spring 3.2, so the dependencies you need are:

  • org.springframework:spring-context
  • org.hibernate:hibernate-validator:4.3.1.Final - runtime scope is all you need
  • javax.validation:validation-api:1.0.0.GA
As long as all of those are available, the only thing you need to do is define a bean in your Spring context of type org.springframework.validation.beanvalidation.BeanValidationPostProcessor. This works whether you are using Spring WebMVC or standalone, which has the important side effect that it works in unit tests.

If you do this, then you can start to add all the fancy @NotNull and similar annotations to your beans, and Spring will ensure they are actually valid when the context is loaded.