javax.validation.Validation is the entry point class for the Bean Validation API (JSR-303/JSR-380). It provides factory methods to create validator instances.
Purpose:
- Creates ValidatorFactory and Validator instances
- Bootstrap the validation framework
- Configure validation providers (like Hibernate Validator)
Key Methods:
1. buildDefaultValidatorFactory()
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
- Creates factory with default configuration
- Uses default validation provider (usually Hibernate Validator)
2. byDefaultProvider()
Validator validator = Validation.byDefaultProvider().configure().buildValidatorFactory().getValidator();
- More control over configuration
- Can customize validation behavior
Common Usage Pattern:
// Get validator instance
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();// Validate an object
Set<ConstraintViolation<User>> violations = validator.validate(user);// Check results
if (violations.isEmpty()) {// Valid object
} else {// Handle violationsviolations.forEach(v -> System.out.println(v.getMessage()));
}
What it validates:
- Fields annotated with @NotNull, @Size, @Email, etc.
- Custom constraints like your @Password annotation
- Nested object validation with @Valid
Dependencies:
- Requires Bean Validation implementation (Hibernate Validator)
- Provided by spring-boot-starter-validation
The Validation class is the standard way to programmatically validate objects in Java.