Sub topic 2
Jakarta Bean Validation and the validation starter
This chapter explains what Jakarta Bean Validation is, how the Spring Boot validation starter adds it to your project, and how to check that it works before you wire it into controllers.
It assumes you know Java records and annotations, can build a simple Spring MVC controller, and can edit a Maven or Gradle build file. It also assumes you know basic HTTP status codes. The examples target Spring Boot 3 or later.
What Bean Validation is
Bean Validation is a specification. It defines a set of annotations such as @NotBlank and @Min. It also defines an API for checking an object against the rules those annotations declare. A specification contains no checking logic of its own, so you need an implementation.
The specification has gone by two names:
- Bean Validation was the name up to version 2.0. Its package was
javax.validation. - Jakarta Bean Validation is the name from version 3.0 on, after Java EE moved to the Eclipse Foundation and became Jakarta EE. Its package is
jakarta.validation.
Spring Boot 3 requires the jakarta.validation packages. Spring Boot 2 uses javax.validation. The annotations have the same names in both, so the only visible difference is the import line.
Hibernate Validator is the reference implementation. It has nothing to do with the Hibernate ORM, although both come from the same project family. Your code depends on the jakarta.validation API, and Hibernate Validator does the work at runtime.
What the starter adds
Since Spring Boot 2.3, spring-boot-starter-web no longer includes validation. You must add the validation starter yourself.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>The Gradle equivalent is:
implementation 'org.springframework.boot:spring-boot-starter-validation'You don't set a version. The Spring Boot dependency management picks versions that work together.
The starter brings in three things:
| Dependency | Role |
|---|---|
| `jakarta.validation-api` | The annotations and the `Validator` interface you code against |
| `hibernate-validator` | The implementation that evaluates constraints |
| An Expression Language implementation (`tomcat-embed-el`) | Lets Hibernate Validator interpolate message templates such as `{max}` and `${validatedValue}` |
The Expression Language dependency is easy to overlook. Without one, Hibernate Validator fails at startup with an error about a missing ExpressionFactory.
What Spring Boot configures for you
Spring Boot's ValidationAutoConfiguration registers a LocalValidatorFactoryBean when it finds a Bean Validation provider on the classpath. This bean is Spring's wrapper around the provider. It implements both jakarta.validation.Validator and Spring's own org.springframework.validation.Validator. Its main benefit is that it creates constraint validators through Spring, so a custom ConstraintValidator can have dependencies injected. A later chapter uses this.
The auto-configuration also registers a MethodValidationPostProcessor. It enables constraints on method parameters of beans annotated with @Validated, which later chapters rely on.
How a constraint is evaluated
A constraint annotation is only metadata. Evaluation follows these steps:
- You ask a
Validatorto validate an object. - The provider reads the annotations on the object's class and builds a model of its constraints. It caches this model per class.
- For each constrained element, the provider finds a
ConstraintValidatorimplementation registered for that annotation and that element type, and calls itsisValidmethod. - The provider collects every failure as a
ConstraintViolationand returns them all in aSet.
validate does not throw an exception when a rule fails. It returns the full set of violations. An empty set means the object is valid. Every constraint is checked, so one call reports all the problems and not only the first.
Each ConstraintViolation gives you the information you need to build an error response:
getPropertyPath()is the location of the failure, such asage.getMessage()is the interpolated message, such asmust be greater than or equal to 18.getInvalidValue()is the value that failed.getConstraintDescriptor()describes the annotation that failed.
Checking the setup
Before you add controllers, confirm that the validator works. This runner uses the CreateUserRequest record from the next chapter, repeated here so the example is complete. Put all three types in one package of a Spring Boot application that has the starter on its classpath.
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validator;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import java.util.Comparator;
import java.util.Set;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
record CreateUserRequest(
@NotBlank @Size(max = 50) String name,
@NotBlank @Email String email,
@NotNull @Min(18) Integer age) {
}
@Component
class ValidationSmokeTest implements CommandLineRunner {
private final Validator validator;
ValidationSmokeTest(Validator validator) {
this.validator = validator;
}
@Override
public void run(String... args) {
CreateUserRequest bad = new CreateUserRequest("", "not-an-email", 15);
Set<ConstraintViolation<CreateUserRequest>> violations = validator.validate(bad);
violations.stream()
.sorted(Comparator.comparing(v -> v.getPropertyPath().toString()))
.forEach(v -> System.out.println(v.getPropertyPath() + ": " + v.getMessage()));
}
}With default English messages, the output is:
age: must be greater than or equal to 18
email: must be a well-formed email address
name: must not be blankThe runner sorts the violations because a Set has no guaranteed order. Your error responses should sort them too, or collect them into an ordered structure, so clients get stable output.
Rules to know early
Several behaviors surprise people on first use.
Most constraints accept null
Only @NotNull, @NotEmpty and @NotBlank reject null. @Email, @Size, @Min and the rest treat null as valid. This is deliberate, because it lets you combine "is it present" and "is it well formed" as separate rules. Compare these two declarations:
@Email String emailaccepts a missing email.@NotBlank @Email String emailrequires one.
Annotations on records reach the right places
When you annotate a record component, Java copies the annotation to the field, the accessor method and the constructor parameter, wherever the annotation's @Target allows. Hibernate Validator reads the field, so constraints on record components work without extra setup. This needs a reasonably recent Hibernate Validator, which any current Boot release provides.
Constraints must match the type
Each constraint supports specific types. @Size works on strings, collections, maps and arrays. @Min works on numeric types but not on String. Putting a constraint on an unsupported type fails with UnexpectedTypeException and the message "No validator could be found for constraint". The failure happens when the object is first validated, not at startup. A test that validates each DTO once catches this early.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Annotations are silently ignored | The starter is missing, so no provider is on the classpath | Add `spring-boot-starter-validation` |
| `package javax.validation does not exist` | Spring Boot 3 project using old imports | Change to `jakarta.validation` |
| Startup error about `ExpressionFactory` | An Expression Language implementation is missing | Use the starter, or add an EL dependency |
| `UnexpectedTypeException` | Constraint applied to an unsupported type | Use a constraint that supports the type, or write a custom one |
| Invalid input reaches the method body | Nothing triggers validation | Covered in the chapter on `@Valid` |
Exercise
Exercise
You add @Email to a String email field and send a request with no email value, so the field is null. Validation passes. Why, and what do you change to reject the request?
Show answer
@Email treats null as valid, like most constraints other than @NotNull, @NotEmpty and @NotBlank. Add @NotBlank (or @NotNull) so a missing value is its own violation: @NotBlank @Email String email.
Exercise
A teammate upgrades a project from Spring Boot 2.7 to 3.2. The code compiles after they switch imports to jakarta.validation, but no constraint is ever enforced. Name two things to check.
Show answer
First, confirm spring-boot-starter-validation is a dependency, because without a provider on the classpath nothing evaluates the annotations. Second, confirm every constraint import uses jakarta.validation.constraints, because Hibernate Validator 7 and later does not process javax.validation annotations.