Friday, January 25, 2013

Annotation based validation with JSR 303 (Bean Validation)

Every time you work with objects, you might want to ensure their state (properties, also referred as collaborators) is valid. So when you build an object based on some given input, you must validate whether this input is appropriate.

JSR 303 (AKA Bean Validation) is an specification defined by the Java Community Process, with the purpose of having an standard mean for validating an object state. 
The idea behind this specification is to use annotations for declaring which restrictions or constraints are applied to an specific object property or even to the whole object. So instead of using some if(...) stuff, you use annotations in the object definition (the class).
As any specification, the community provides a high level design (some documents, interfaces, abstract classes, etc.) and let the vendors implement the details. In the case of JSR 303 there are two main implementations: Apache BVal and Hibernate Validator.

So let's take a peek:

public class Person {

         @NotNull
         private String name;

         ...
}