Generic JavaBeans Validation
External
Internal
Overview
This article documents a runnable Java example uses JavaBeans Validation annotations to externalize validation logic to a JavaBeans validation provider. The example depends on Spring Boot, but this is only because we use Spring Boot's machinery to pull starter dependencies, including Hibernate Validator, and get our runtime running. There is nothing Spring-specific that would prevent the same example working in a generic Java environment with JSR-303 support.
Approach
Spring Boot Starter Dependencies
The simplest way to get the project started is to use Spring Initializr and select "Validation". The Gradle configuration will get the following dependency:
dependencies {
...
implementation('org.springframework.boot:spring-boot-starter-validation')
...
}
Declare Validation Rules
Use JavaBean Validation annotation to declare validation logic. Example:
public class CreditCard {
...
@NotNull(message = "The first name cannot be null")
private String firstName;
...
}
A certain number of standard validation annotations are available:
Because we are using Hibernate Validator, Hibernate-specific validation annotations are also available:
Instantiate a Validator
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
...
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
...
Validate and Handle Constraint Violations
import javax.validation.ConstraintViolation;
...
CreditCard cc = new CreditCard();
Set<ConstraintViolation<CreditCard>> violations = validator.validate(cc);
for(ConstraintViolation<CreditCard> v: violations) {
System.out.println(v.getMessage());
}
...
The result of validating a CardAccount with a null first name is:
The first name cannot be null
at stdout.