Hibernate Validator CDI – @HibernateValidator Example

Java example of hibernate validator CDI to inject default Java bean validation classes implementations e.g. javax.validation.ValidatorFactory and javax.validation.Validator with hibernate-validator-cdi dependency. Also learn to inject specialized validator if application has multiple validator implementations like org.hibernate.validator.cdi.HibernateValidator.

Please note that if your application runs in an environment which provides this integration out of the box, then you do not need to add additional dependencies to run this example. For example, spring framework provides such CDI infrastructure implicitly, so don’t use hibernate validator CDI with Spring framework.

For other applications, such as standalone Java applications, you may need it to create HibernateValidator using annotations.

1. Hibernate Validator CDI Maven Dependency

All necessary dependencies to work with hibernate validator are listed below.

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd;





2. Model class annotated with validation annotations

A simple Java class with field validation annotations.

package com.howtodoinjava.example.model;

import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

public class User {

    @NotNull(message = "Please enter id")
    private Long id;

    @Size(max = 20, min = 3, message = "{user.name.invalid}")
    @NotEmpty(message = "Please enter name")
    private String name;

    @Email(message = "{user.email.invalid}")
    @NotEmpty(message = "Please enter email")
    private String email;

    public User(Long id, String name, String email) {
        this.id = id;
        this.name = name;
        this.email = email;

	//Getters and Setters

    public String toString() {
        return "User [id=" + id + ", name=" + name + ", email=" + email + "]";

3. Inject default and hibernate javax.validation.Validator

Inject ValidatorFactory and Validator using @Inject annotations. The injected beans are the default validator factory and validator instances.

private static ValidatorFactory validatorFactory;

private static Validator validator;

If you are working with several Bean Validation providers, you can make sure that factory and validator from Hibernate Validator are injected by annotating the injection points with the @HibernateValidator qualifier.

import org.hibernate.validator.cdi.HibernateValidator;

private static ValidatorFactory validatorFactory;

private static Validator validator;

4. How to validate beans

An example to use injected validator to validate Java beans and check error messages.

package com.howtodoinjava.example;

import java.util.Set;

import javax.inject.Inject;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import org.hibernate.validator.cdi.HibernateValidator;

import com.howtodoinjava.example.model.User;

public class TestHibernateValidator 
    private static ValidatorFactory validatorFactory;

    private static Validator validator;
    public static void main(String[] args) 
        //Create ValidatorFactory which returns validator
        validatorFactory = Validation.buildDefaultValidatorFactory();
        //It validates bean instances
        validator = validatorFactory.getValidator();

        User user = new User(null, "1", "abcgmail.com");

        //Validate bean
        Set<ConstraintViolation<User>> constraintViolations = validator.validate(user);

        //Show errors
        if (constraintViolations.size() > 0) {
            for (ConstraintViolation<User> violation : constraintViolations) {
        } else {
            System.out.println("Valid Object");

Program output:

Aug 06, 2018 12:25:17 PM org.hibernate.validator.internal.util.Version <clinit>
INFO: HV000001: Hibernate Validator 6.0.11.Final

Please enter id
'1' is an invalid name. It must be minimum 3 chars and maximum 20 chars.
Invalid Email

Above example fetches resource messages from property file in classpath.

user.name.invalid='${validatedValue}' is an invalid name. It must be minimum {min} chars and maximum {max} chars.
user.email.invalid=Invalid Email

5. Summary

In above example, we learn the following:

  • How we can include hibernate validator CDI dependency and use it.
  • How to inject default validator factory and validator instances.
  • How to inject specialized validator factory and validator instances, if there are more than one Java bean validator implementations. e.g. in above case, it’s hibernate validator.
  • How to validate Java beans using annotations configuration.

Happy Learning !!

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

Leave a Comment


A blog about Java and related technologies, the best practices, algorithms, and interview questions.