Java Bean validation is annotation based object validation framework.
To validate a bean we need to
- Place validation annotation on the fields to be validated. Other than fields we can also use them on method/constructor parameters, on method return type or on class level.
- Get an instance of javax.validation.Validator
- Call
Validator#validate() method to trigger validation process
The validation annotations are also referred as 'constraints'.
Validator is the main interface to kick off the validation process and to find out validation errors (violations).
This specification has been defined as a part JSR 380, 349 and JSR 303.
The reference implementation is Hibernate Validator Engine. So we need following maven dependencies to run any validation related code:
pom.xml<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.2.0.Final</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.el</artifactId>
<version>3.0.0</version>
</dependency>
Working with constraints and validation violations
Creating bean with constraints:
import javax.validation.constraints.*;
public class MyBean{
@NotNull
private String strField
//getters and setters
}
In the above, snippet we used @NotNull. This annotation is one of the the predefined constraint annotations.
Bootstrapping and getting instance of javax.validation.Validator
import javax.validation.*
....
Configuration<?> config = Validation.byDefaultProvider().configure();
ValidatorFactory factory = config.buildValidatorFactory();
Validator validator = factory.getValidator();
factory.close();
Perform validations
Validator validator = ...
.....
MyBean myBean MyBean();
.....
Set<ConstraintViolation<MyBean>> violations = validator.validate(myBean);
violations.forEach(v -> System.out.println(v.getPropertyPath() +
"- " + v.getMessage()));
Complete Example
package com.logicbig.example;
import javax.validation.*;
import javax.validation.constraints.NotNull;
public class BeanFieldValidationExample {
private static final Validator validator;
static {
Configuration<?> config = Validation.byDefaultProvider().configure();
ValidatorFactory factory = config.buildValidatorFactory();
validator = factory.getValidator();
factory.close();
}
private static class MyBean {
@NotNull
private String str;
public String getStr () {
return str;
}
public void setStr (String str) {
this.str = str;
}
}
public static void main (String[] args) {
MyBean myBean = new MyBean();
validator.validate(myBean).stream()
.forEach(BeanFieldValidationExample::printError);
}
private static void printError (ConstraintViolation<MyBean> violation) {
System.out.println(violation.getPropertyPath()
+ " " + violation.getMessage());
}
}
Outputstr must not be null
As saw in above example, javax.validation.ConstraintViolation is used to access validation messages. This object also exposes other details about the validation errors.
Field-level vs Property-level constraints
In above example, we used constraint annotation @NotNull on field level. We can also put constraints on getters, unless if they are not defined with @Target having ElementType.METHOD.
Constraints used on getters are referred as 'property-level' constraints. In this case performing validation will be the same as described above i.e. by calling validator.validate(..) method and get the validation violations.
Property-level constrains example
package com.logicbig.example;
import javax.validation.*;
import javax.validation.constraints.NotNull;
public class BeanPropertyValidationExample {
private static final Validator validator;
static {
Configuration<?> config = Validation.byDefaultProvider().configure();
ValidatorFactory factory = config.buildValidatorFactory();
validator = factory.getValidator();
factory.close();
}
private static class MyBean {
private String str;
@NotNull
public String getStr () {
return str;
}
public void setStr (String str) {
this.str = str;
}
}
public static void main (String[] args) {
MyBean myBean = new MyBean();
validator.validate(myBean).stream()
.forEach(BeanPropertyValidationExample::printError);
}
private static void printError (ConstraintViolation<MyBean> violation) {
System.out.println(violation.getPropertyPath()
+ " " + violation.getMessage());
}
}
Outputstr must not be null
Example ProjectDependencies and Technologies Used: - hibernate-validator 6.2.0.Final (Hibernate's Jakarta Bean Validation reference implementation)
Version Compatibility: 5.0.0.Final - 6.2.0.Final Version compatibilities of hibernate-validator with this example: groupId: org.hibernate artifactId: hibernate-validator (Reference implementation for Bean Validation 1.1)
- 5.0.0.Final
- 5.0.1.Final
- 5.0.2.Final
- 5.0.3.Final
- 5.1.0.Final
- 5.1.1.Final
- 5.1.2.Final
- 5.1.3.Final
- 5.2.0.Final
- 5.2.1.Final
- 5.2.2.Final
- 5.2.3.Final
- 5.2.4.Final
- 5.2.5.Final
- 5.3.0.Final
- 5.3.1.Final
- 5.3.2.Final
- 5.3.3.Final
- 5.3.4.Final
- 5.3.5.Final
- 5.3.6.Final
- 5.4.0.Final
- 5.4.1.Final
- 5.4.2.Final
- 5.4.3.Final
groupId: org.hibernate.validator artifactId: hibernate-validator (Reference implementation for Bean Validation 2.0)
- 6.0.0.Final
- 6.0.1.Final
- 6.0.2.Final
- 6.0.3.Final
- 6.0.4.Final
- 6.0.5.Final
- 6.0.6.Final
- 6.0.7.Final
- 6.0.8.Final
- 6.0.9.Final
- 6.0.10.Final
- 6.0.11.Final
- 6.0.12.Final
- 6.0.13.Final
- 6.0.14.Final
- 6.0.15.Final
- 6.0.16.Final
- 6.0.17.Final
- 6.0.18.Final
- 6.0.19.Final
- 6.0.20.Final
- 6.0.21.Final
- 6.0.22.Final
- 6.1.0.Final
- 6.1.1.Final
- 6.1.2.Final
- 6.1.3.Final
- 6.1.4.Final
- 6.1.5.Final
- 6.1.6.Final
- 6.1.7.Final
- 6.2.0.Final
Version 7 and later: Jakarta Bean Validation 3.0 jakarta.* packages
Versions in green have been tested.
- javax.el 3.0.0 (Expression Language 3.0)
- JDK 8
- Maven 3.8.1
|