Sub topic 5
Validating records with Bean Validation
This chapter shows how to put Bean Validation constraints on record components and make Spring enforce them on incoming request bodies. It assumes you know basic Java, can write a Spring Boot @RestController with @PostMapping, and have seen records used as request and response DTOs. You need Java 17 or later and the spring-boot-starter-validation dependency. Spring Boot Web does not include it.
Why validate at the DTO
A request DTO is the boundary where untrusted JSON enters your application. If you check the data there, the service layer can assume it is well formed. Bean Validation (the Jakarta Validation standard, implemented by Hibernate Validator) lets you declare the rules as annotations instead of writing if checks by hand.
Constraints on record components
You place constraint annotations directly on the record components. Java copies them to the places where validators look for them, so no extra setup is needed.
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) {
}Some constraints you will use often:
| Annotation | Checks | Applies to |
|---|---|---|
| `@NotNull` | Value is not null | Any object |
| `@NotBlank` | Not null and has a non-whitespace character | Strings |
| `@Size(min, max)` | Length or element count within bounds | Strings, collections |
| `@Min`, `@Max` | Numeric bounds | Numbers |
| `@Email` | Looks like an email address | Strings |
@Email accepts null and empty strings, so combine it with @NotBlank when the field is required, as the example does.
Triggering validation with @Valid
Constraints do nothing until something asks the validator to run. In a controller, add @Valid to the @RequestBody parameter.
import jakarta.validation.Valid;
import java.net.URI;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/users")
class UserController {
private final UserService service;
UserController(UserService service) {
this.service = service;
}
@PostMapping
ResponseEntity<UserResponse> create(@Valid @RequestBody CreateUserRequest request) {
UserResponse created = service.create(request);
return ResponseEntity.created(URI.create("/users/" + created.id())).body(created);
}
}The order of events is:
- Jackson builds a
CreateUserRequestfrom the JSON. - Spring runs the validator on the new record.
- If any constraint fails, Spring throws
MethodArgumentNotValidExceptionand the controller method never runs. By default the response is400 Bad Request. - If all constraints pass, the method runs normally.
Note that validation happens after construction. If the record has a compact constructor that throws, the failure occurs in step 1, before any constraint is checked. A later chapter covers compact constructors in detail. For now, keep value rules in annotations and reserve constructors for normalization.
Validating nested records and collections
Validation does not descend into nested objects by default. Mark the component with @Valid to cascade into it. For collections, put the constraint on the type argument.
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.Positive;
import java.util.List;
public record OrderRequest(
@NotBlank String customerId,
@NotEmpty List<@Valid OrderLine> lines) {
}
record OrderLine(@NotBlank String sku, @Positive int quantity) {
}Without @Valid on the element type, a line with quantity -3 passes silently.
Reading the errors
The default 400 body does not list each field in a form clients can easily use. To return your own, handle the exception in a @RestControllerAdvice.
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
class ValidationErrorHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
Map<String, String> handle(MethodArgumentNotValidException ex) {
return ex.getBindingResult().getFieldErrors().stream()
.collect(Collectors.toMap(
e -> e.getField(),
e -> String.valueOf(e.getDefaultMessage()),
(first, second) -> first));
}
}The merge function (first, second) -> first matters. A field with two failed constraints produces two errors with the same key, and toMap throws IllegalStateException on duplicates without it.
Common errors
- Nothing is validated. Either
@Validis missing on the parameter, or the validation starter is not on the classpath. - A primitive hides a missing field. If
ageis declaredint, a missing JSON property becomes0, not null. UseIntegerwith@NotNullwhen you must tell "absent" from "zero". @NotNullon a primitive. It never fails, because a primitive cannot be null.- Wrong import. Spring Boot 3 uses
jakarta.validation. The olderjavax.validationpackage is silently ignored.
Exercise
A request record declares @Min(1) int quantity. A client sends JSON with no quantity property, and the controller parameter has @Valid. Why does the request fail with a 400, and what would happen if the constraint were @Min(0)?
Show answer
A missing property on a primitive int component becomes the default value 0. With @Min(1), 0 violates the constraint, so Spring throws MethodArgumentNotValidException and returns 400. With @Min(0), 0 is valid, so the request passes and the missing field goes unnoticed. To reject a missing value, declare Integer quantity with @NotNull.
Exercise
Given record Basket(@NotEmpty List<OrderLine> lines), where OrderLine has @Positive int quantity, a request contains one line with quantity -3. Does validation fail? How do you fix it?
Show answer
It does not fail. Validation does not cascade into the list elements by default. Change the component to @NotEmpty List<@Valid OrderLine> lines so each element is validated.