Bean Validation JSR 349 Standalone Example

[Last Updated: Feb 6, 2017]

JavaBean Validation JAVA EE 

Add Hibernate Validator (the reference implementation) dependency in pom.xml


We don't have to add javax.validation api as Hibernate pulls that in transitively. But we would need this one


Define Bean and add JSR 349 constraints annotations:

package com.logicbig.example;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Past;
import java.util.Date;

public class Person {
private String name;

private int age;

private Date dateOfBirth;

//getter and setters


Bootstrap ValidatorFactory.

import javax.validation.*;
import java.util.Date;
import java.util.Set;

public class BeanValidationExample {
public static void main (String[] args) {
Configuration<?> config = Validation.byDefaultProvider()
ValidatorFactory factory = config.buildValidatorFactory();
Validator validator = factory.getValidator();

Person person = new Person();
person.setDateOfBirth(new Date(System.currentTimeMillis() + 10000));

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

Notice all above method calls are of javax.validation not Hibernate but the underlying implementation is Hibernate.

The loading of implementation is based on SPI pattern.


Feb 22, 2016 7:00:47 PM org.hibernate.validator.internal.util.Version <clinit>
INFO: HV000001: Hibernate Validator 5.2.4.Final
dateOfBirth- must be in the past
age- must be greater than or equal to 1
name- may not be null

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
  • JDK 1.8
  • Maven 3.0.4

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

    See Also