What is Bean Validation?
Bean Validation (Jakarta Bean Validation specification, formerly JSR 380) is a standard framework for data validation in Java applications. It allows you to declaratively describe validation rules for fields, methods, and classes using annotations. The most popular implementation is Hibernate Validator.
Why is validation needed?
In any application that works with user input, it is necessary to check data: whether a string is empty, whether a number falls within a range, whether an email is correct. Manual checking using if-else makes the code cumbersome and difficult to maintain. Bean Validation solves this problem by moving validation logic into annotations and ensuring uniform error handling.
How to install
If you are using Maven, add to pom.xml:
<dependency><groupId>org.hibernate.validator</groupId><artifactId>hibernate-validator</artifactId><version>8.0.1.Final</version></dependency>For Gradle:
implementation 'org.hibernate.validator:hibernate-validator:8.0.1.Final'In Spring Boot, validation is already pre-installed.
Main features
- Standard annotations: @NotNull, @Size, @Min, @Max, @Email, @Pattern, @Positive, @NotBlank and others.
- Validation groups: allow you to apply different rules depending on the context (e.g., creation vs update).
- Custom validators: you can create your own annotation and write validation logic.
- Method parameter validation: checking arguments and return values.
Java code example
import jakarta.validation.constraints.*;import jakarta.validation.*;
public class User { @NotBlank(message = "Name cannot be empty") private String name;
@Email(message = "Invalid email") private String email;
@Min(18) @Max(120) private int age;
// getters and setters}
// UsageValidatorFactory factory = Validation.buildDefaultValidatorFactory();Validator validator = factory.getValidator();
User user = new User();user.setEmail("invalid");
Set<ConstraintViolation<User>> violations = validator.validate(user);for (ConstraintViolation<User> violation : violations) { System.out.println(violation.getMessage());}When to use
Bean Validation is used in REST APIs (Spring Boot, Jakarta EE), web forms, DTO objects, and when working with databases. It is indispensable if you want to guarantee data integrity at the Java code level before saving it. It is recommended for all projects where there is user input or integration with external systems.