Sub topic 3
Validating Nested Objects and Collections
Assume you know Java records, annotations, Spring MVC controllers, and Maven dependencies. This chapter focuses on validation that goes beyond simple fields.
Validating nested objects and collections
Bean Validation does not automatically inspect nested objects. Add @Valid to enable cascading validation. For collections, place @Valid on the collection field and on its element type when needed.
public record OrderRequest(
@NotBlank String customerId,
@NotEmpty List<@Valid OrderLine> lines) {
}
public record OrderLine(
@NotBlank String sku,
@Positive int quantity) {
}@NotEmpty checks the list itself. @Valid checks every OrderLine. A failed nested field appears in the binding errors with a path such as lines[0].sku.
flowchart TD
A[HTTP request] --> B[OrderRequest]
B --> C[Validate customerId]
B --> D[Validate each OrderLine]
D --> E[Validate sku and quantity]Writing a custom constraint
Use a custom constraint when standard annotations cannot express a rule.
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.RECORD_COMPONENT})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = AllowedCountryValidator.class)
public @interface AllowedCountry {
String message() default "{country.unsupported}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
final class AllowedCountryValidator
implements ConstraintValidator<AllowedCountry, String> {
private static final Set<String> SUPPORTED = Set.of("DE", "FR", "US");
public boolean isValid(String value, ConstraintValidatorContext context) {
return value == null || SUPPORTED.contains(value);
}
}Return true for null unless this constraint owns requiredness. Combine it with @NotNull when null is invalid.
Customizing and externalizing messages
Constraint messages can use keys from messages.properties:
country.unsupported=Country must be DE, FR, or USThis separates code from presentation and supports localization. A @RestControllerAdvice can return these messages in a consistent ProblemDetail response.
Using validation groups for create and update
Groups select different rules for different operations.
interface OnCreate {}
interface OnUpdate {}
public record UserRequest(
@NotBlank(groups = OnCreate.class) String username,
@NotBlank(groups = {OnCreate.class, OnUpdate.class}) String email) {
}Activate a group with @Validated(OnCreate.class) on a controller method. Use groups sparingly because they add coupling between the DTO and its workflows.
Cross-field rules with class-level constraints
A rule involving multiple fields belongs on the class or record, such as requiring an end date after a start date. The validator receives the complete object and can attach a violation to a chosen property.
Validating beyond the controller
Annotate service methods with @Validated when validation must also apply to non-HTTP callers. Method constraints then protect scheduled jobs, messaging consumers, and internal calls. Remember that proxy-based validation applies when calls pass through the Spring proxy.
Testing validation
Use MockMvc to verify HTTP status codes and JSON error paths. Use a plain jakarta.validation.Validator test for a custom validator without starting Spring.
| Test target | Useful check |
|---|---|
| Nested request | `lines[0].sku` is reported |
| Custom validator | Unsupported country produces one violation |
Exercise
What two annotations validate a non-empty list and each object inside it?
Show answer
Use @NotEmpty on the list and @Valid on its element type or collection field.