Warning:BindingResult parameter MUST be immediately after the
validated argument.
8. Customizing Validation Messages
Example: Custom validation message bundle
# src/main/resources/ValidationMessages.propertiesNotBlank.user.email=Email is requiredSize.user.password=Password must be {min} to {max} charactersjavax.validation.constraints.Email.message=Provide a valid email address
Format
Description
{min}, {max}, {value}
Constraint params
{NotBlank.user.email}
Inheritable message keys
SpEL ${}
Expression evaluation
9. Using Validation Groups
Example: Validation groups for create vs update
public interface OnCreate {}public interface OnUpdate {}public record User( @Null(groups=OnCreate.class) @NotNull(groups=OnUpdate.class) Long id, @NotBlank String email) {}@PostMappingResponseEntity<?> create(@Validated(OnCreate.class) @RequestBody User u) { /* … */ }
10. Validating Nested Objects (@Valid on fields)
Example: Nested object and list validation
public record Order( @NotNull @Valid Customer customer, @NotEmpty @Valid List<@Valid LineItem> items) {}
Pattern
Effect
@Valid on field
Cascade into nested object
List<@Valid X>
Element-level cascade (Bean Val 2+)
11. Using @Validated for Method-Level Validation
Example: Method-level validation on service
@Service@Validatedpublic class UserService { public User load(@NotBlank String email) { /* … */ } public @NotNull User update(@Valid UserUpdate u) { /* … */ }}
Note: Throws ConstraintViolationException; handle in
@ControllerAdvice.