Sub topic 5
Validating records with Bean Validation
This chapter shows how to put validation rules on a record DTO and have Spring enforce them before your controller code runs. It assumes you can write a Spring Boot REST controller and that you know record syntax and how Jackson binds JSON to a record, which earlier chapters covered. You need Java 17 or later and Spring Boot 3.x, which uses the jakarta.validation package.
What Bean Validation does
Bean Validation is a Jakarta standard for declaring constraints as annotations, such as @NotBlank or @Min. Hibernate Validator is the reference implementation, and Spring Boot configures it for you. The annotations describe what a valid object looks like. A separate component, the Validator, reads them and reports violations.
Records suit this well. A record's components are its only state, so the constraints sit right next to the data they protect, and the compact form keeps the DTO to a few lines.
Add the starter to your build:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>Without it, @Valid is silently ignored in some setups because no validator is on the classpath. Adding the starter is the first thing to check when validation seems to do nothing.
Constraints on record components
You write the annotation on the record component:
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
public record CreateUserRequest(
@NotBlank @Size(max = 50) String name,
@NotBlank @Email String email,
@Min(18) int age) {
}A record component is shorthand for several members: a private field, an accessor method, and a parameter of the canonical constructor. Java copies an annotation from the component to each of these places where the annotation's @Target allows it. Constraint annotations permit FIELD, METHOD, and PARAMETER, so they land on all three. Hibernate Validator then validates the field values. The accessor name() doesn't follow the JavaBeans getter naming, so it is not validated a second time. You don't need to write @field: or similar prefixes, which Kotlin requires.
Choosing between primitives and wrappers
The example above has a trap. @Min(18) int age cannot tell "age missing" from "age is 0". When the JSON has no age property, Jackson passes the primitive default 0. The request fails, but the message says the age is too low, not that it is missing. Use a wrapper type and add @NotNull:
public record CreateUserRequest(
@NotBlank @Size(max = 50) String name,
@NotBlank @Email String email,
@NotNull @Min(18) Integer age) {
}Most constraints treat null as valid, so that @Min or @Size only check a value that is present. @NotNull, @NotBlank, and @NotEmpty are the ones that reject null. Pair them with the other constraints when a field is required.
| Constraint | Applies to | Rejects `null` | Notes |
|---|---|---|---|
| `@NotNull` | any type | yes | Only checks for `null`. |
| `@NotEmpty` | `String`, collections, maps, arrays | yes | Rejects length or size 0. |
| `@NotBlank` | `CharSequence` | yes | Rejects `null`, empty, and whitespace-only strings. |
| `@Size(min, max)` | `String`, collections, maps, arrays | no | `null` passes. |
| `@Min`, `@Max` | numbers | no | `null` passes. |
| `@Email` | `CharSequence` | no | A loose format check. |
| `@Pattern(regexp)` | `CharSequence` | no | The regex must match the whole value. |
Triggering validation with @Valid
Declaring constraints does nothing by itself. Validation runs when something asks for it. In a controller that something is @Valid on the @RequestBody parameter:
@PostMapping
ResponseEntity<UserResponse> create(@Valid @RequestBody CreateUserRequest request) {
UserResponse created = service.create(request);
return ResponseEntity.created(URI.create("/users/" + created.id())).body(created);
}Spring's message converter first uses Jackson to build the record. Then the argument resolver validates it. If any constraint fails, Spring throws MethodArgumentNotValidException before the method body runs. By default this becomes a 400 Bad Request response.
The order matters. The record's constructor, including any compact constructor logic, always runs before Bean Validation. Two consequences follow:
- Normalization in a compact constructor is visible to the constraints. If the constructor strips whitespace,
@NotBlanksees the stripped value. - If the constructor itself throws, validation never happens. Jackson wraps the exception and Spring responds with
HttpMessageNotReadableException, a different error path thanMethodArgumentNotValidException.
Returning useful error responses
The default 400 body is acceptable for a prototype, but clients usually want to know which fields failed. A @RestControllerAdvice can turn the exception into an RFC 9457 ProblemDetail:
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
class ValidationExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
ProblemDetail handleValidation(MethodArgumentNotValidException ex) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
HttpStatus.BAD_REQUEST, "Request validation failed");
Map<String, String> errors = new LinkedHashMap<>();
for (FieldError error : ex.getBindingResult().getFieldErrors()) {
errors.putIfAbsent(error.getField(), error.getDefaultMessage());
}
problem.setProperty("errors", errors);
return problem;
}
}For a request with a blank name and an underage user, the response body looks like this (the order of entries can vary):
{
"type": "about:blank",
"title": "Bad Request",
"status": 400,
"detail": "Request validation failed",
"instance": "/users",
"errors": {
"name": "must not be blank",
"age": "must be greater than or equal to 18"
}
}Several constraints can fail on one field, for example an empty string fails both @NotBlank and a @Size(min = 3). The handler uses putIfAbsent to report one message per field. If you want all of them, collect into a Map<String, List<String>> instead.
The default messages are generic. Override them per constraint with the message attribute:
public record LoginRequest(
@NotBlank(message = "username is required") String username,
@NotBlank(message = "password is required") String password) {
}Nested records, collections, and cascading
Validation does not cascade on its own. If a record contains another record, the outer record's constraints run, but the inner record's constraints are skipped unless you mark the component with @Valid:
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern;
import java.util.List;
public record Address(
@NotBlank String street,
@NotBlank String city,
@NotBlank @Pattern(regexp = "\\d{5}") String postalCode) {
}
public record RegisterRequest(
@NotBlank String name,
@NotNull @Valid Address address,
@NotEmpty List<@NotBlank String> tags,
@NotEmpty List<@Valid Address> shippingAddresses) {
}Three things are worth noting here:
@NotNull @Valid Address addressmakes the address required and then validates its contents.@Validalone accepts anulladdress, because cascading skipsnullvalues.List<@NotBlank String>is a container element constraint. It checks each element, not the list.@NotEmptyon the list checks the list itself.List<@Valid Address>cascades into each element. The same placement works forMapvalues andOptional.
Field paths in the errors reflect the nesting: address.city, tags[1], shippingAddresses[0].postalCode. Your handler already passes these through, since FieldError.getField() returns the full path.
Rules that span several fields
Some rules involve more than one component, such as "end date must be after start date". Two options fit records.
The first is @AssertTrue on a boolean method whose name follows the getter convention (isXxx). Hibernate Validator treats it as a property:
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.validation.constraints.AssertTrue;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
public record PasswordChangeRequest(
@NotBlank @Size(min = 12) String newPassword,
@NotBlank String confirmation) {
@JsonIgnore
@AssertTrue(message = "confirmation must match newPassword")
public boolean isConfirmationMatching() {
return newPassword == null || newPassword.equals(confirmation);
}
}@JsonIgnore keeps Jackson from treating confirmationMatching as a property if you ever serialize the record. The newPassword == null check lets the @NotBlank constraint report the missing value instead of this rule. The field error appears under the property name confirmationMatching, which may not match anything in the client's form.
The second option is a custom class-level constraint annotation with its own ConstraintValidator. It gives you control over which field the error attaches to, at the cost of two extra types. Use @AssertTrue for one or two small rules and the custom constraint when the rule is reused or needs precise error paths.
Validating outside the controller
Records are plain objects, so you can validate them anywhere. Inject jakarta.validation.Validator, which Spring Boot registers as a bean, and call it directly:
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validator;
import java.util.Set;
import org.springframework.stereotype.Service;
@Service
class ImportService {
private final Validator validator;
ImportService(Validator validator) {
this.validator = validator;
}
void importUser(CreateUserRequest request) {
Set<ConstraintViolation<CreateUserRequest>> violations = validator.validate(request);
if (!violations.isEmpty()) {
throw new IllegalArgumentException(violations.toString());
}
// continue with the import
}
}This helps for records built from CSV rows or messages from a queue, where no controller argument resolver is involved. To validate parameters of ordinary Spring beans through annotations, put @Validated on the class and @Valid on the parameter. A failure then raises ConstraintViolationException, which needs its own handler.
You can also test constraints without starting Spring:
import static org.assertj.core.api.Assertions.assertThat;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import org.junit.jupiter.api.Test;
class CreateUserRequestValidationTest {
private final Validator validator =
Validation.buildDefaultValidatorFactory().getValidator();
@Test
void rejectsUnderageUser() {
CreateUserRequest request = new CreateUserRequest("Ada", "[email protected]", 17);
var violations = validator.validate(request);
assertThat(violations)
.extracting(v -> v.getPropertyPath().toString())
.containsExactly("age");
}
}This test uses the three-argument constructor with int age from the first version of the record. If you switched to Integer, pass 17 and it autoboxes. The test needs a validator and an expression language implementation on the classpath, which spring-boot-starter-validation provides.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| No validation errors, bad data accepted | `@Valid` missing on the `@RequestBody` parameter | Add `@Valid` (or `@Validated`). |
| Nested record constraints ignored | No `@Valid` on the nested component | Annotate the component, or the type argument for collections. |
| `age` reports "too low" when absent | Primitive `int` defaults to `0` | Use `Integer` with `@NotNull`. |
| 400 with "JSON parse error" instead of field errors | The compact constructor threw, or the JSON type was wrong | Move rule checks into constraints, or handle `HttpMessageNotReadableException`. |
| `NoClassDefFoundError` or "No validation provider" | Missing `spring-boot-starter-validation` | Add the starter. |
| Constraint on a method parameter not enforced | Class lacks `@Validated` | Add `@Validated` to the Spring bean. |
Exercise
A PlaceOrderRequest record has the components String customerId and List<OrderLine> lines, where OrderLine is a record with @NotBlank String sku and @Min(1) int quantity. A client sends {"customerId": "c1", "lines": [{"sku": "", "quantity": 0}]} and the controller accepts it with a 201. What is probably wrong, and how do you fix it so that the response is a 400 and the error paths are lines[0].sku and lines[0].quantity? Also, what should you add so that an empty or missing lines list is rejected?
Show answer
Cascading is not configured. The @Valid annotation is probably missing from the controller parameter, or from the lines component, so the constraints on OrderLine are never checked. Put @Valid @RequestBody PlaceOrderRequest request on the controller method and declare the component as @NotEmpty List<@Valid OrderLine> lines. Add @NotBlank to customerId as well if it is required. @NotEmpty rejects both a missing (null) list and an empty one. With cascading enabled, the failures are reported as lines[0].sku and lines[0].quantity.