Bootstrapping ValidationFactory with Hibernate Validator CDI

Learn to use Hibernate validator CDI (Contexts and Dependency Injection for Jakarta EE) module to inject default bean validation factory implementation i.e. javax.validation.ValidatorFactory and javax.validation.Validator. Also, learn to inject a custom Validator if application has multiple bean validation implementations.

Please note that if our application runs in an environment that provides CDI integration out of the box, then we 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.

1. Dependency

As stated above, include the latest CDI module dependency if it is not already provided by other framework or application server.

<dependency>
    <groupId>org.hibernate.validator</groupId>
    <artifactId>hibernate-validator-cdi</artifactId>
    <version>7.0.4.Final</version>
</dependency>

2. Model

A simple POJO with field constraint annotations. Import these annotations from jakarta.validation.constraints package if we are using Hibernate 6 or later. For earlier versions, use javax.validation.constraints package.

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) {
        super();
        this.id = id;
        this.name = name;
        this.email = email;
    }
 
  //Getters and Setters
 
    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", email=" + email + "]";
    }
}

3. Injecting ValidatorFactory and Validator

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

@Inject
private static ValidatorFactory validatorFactory;
 
@Inject
private static Validator validator;

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

@Inject
@HibernateValidator
private static ValidatorFactory validatorFactory;
 
@Inject
@HibernateValidator
private static Validator validator;

4. Demo

Given below is an example is to use injected validator to validate Java beans and check error messages.

public class TestHibernateValidator 
{
    @Inject
    @HibernateValidator
    private static ValidatorFactory validatorFactory;
 
    @Inject
    @HibernateValidator
    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) {
                System.out.println(violation.getMessage());
            }
        } else {
            System.out.println("Valid Object");
        }
    }
}

Program output:

Aug 06, 2021 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

The above example fetches resource messages from the property file in the 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. Conclusion

In the 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 implementation. e.g. in the above case, it’s hibernate validator.
  • How to validate Java beans using annotations configuration.

Happy Learning !!

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode