Quick concepts of JavaBean Validation framework to get started

[Updated: Aug 6, 2017, Created: Sep 21, 2016]

JavaBean validation is annotation based object validation framework.

We just have to put validation annotations on fields, methods/constructors parameters or on return values, or on a class of a JavaBeans component, then we use the instance of javax.validation.Validator and call it's method validate(..) to trigger the validation on the bean.

The validation annotations are also referred as 'constraints' in this framework

Validator is the main interface to kick off the validation process and to find out validation errors (violations).

This specification has been defined as a part JSR 349 and JSR 303.

The reference implementation is Hibernate Validator Engine. So we need following maven dependencies to run any validation related code:


Working with constraints and validation violations

Creating bean with constraints:

 import javax.validation.constraints.*;

 public class MyBean{
    private String strField
    //getters and setters

In the above, snippet we used @NotNull. This annotation is one of the the predefined constraint annotations.

Bootstrapping and getting instance of javax.validation.Validator

    import javax.validation.*
    Configuration<?> config = Validation.byDefaultProvider().configure();
    ValidatorFactory factory = config.buildValidatorFactory();
    Validator validator = factory.getValidator();

Perform validations

     Validator validator = ...
    MyBean myBean MyBean();
    Set<ConstraintViolation<MyBean>> violations = validator.validate(myBean);
       violations.forEach(v -> System.out.println(v.getPropertyPath() +
                                                      "- " + v.getMessage()));

As saw in above example, javax.validation.ConstraintViolation is used to access validation messages. This object also exposes other details about the validation errors.

Field-level vs Property-level constraints

In above example, we used constraint annotation @NotNull on field level. We can also put constraints on getters, unless if they are not defined with @Target having ElementType.METHOD.

Constraints used on getters are referred as 'property-level' constraints. In this case performing validation will be the same as described above i.e. by calling validator.validate(..) method and get the validation violations.

Example project

Example Project

Dependencies and Technologies Used :

  • Hibernate Validator Engine 5.2.4.Final: Hibernate's Bean Validation (JSR-303) reference implementation.
  • Expression Language API 2.2 2.2.4
  • Expression Language 2.2 Implementation 2.2.4
  • JDK 1.8
  • Maven 3.0.4

Bean Validation Examples Select All Download
  • java-bean-validation
    • src
      • main
        • java
          • com
            • logicbig
              • example

See Also