Video in progress
What is the difference between @Valid and @Validated?
@Valid comes from Jakarta Bean Validation: it makes the object and the nested objects inside it get validated. @Validated comes from Spring: it knows about groups, and on a class it also validates method parameters.
📖 Answer
public record SignupRequest(
@NotBlank String name,
@Email String email,
@Valid AddressDto address) {} // validate the nested object too
@RestController
class SignupController {
@PostMapping("/signup")
void signup(@Valid @RequestBody SignupRequest req) { ... }
}
@Valid |
@Validated |
|
|---|---|---|
| Comes from | jakarta.validation |
org.springframework.validation.annotation |
| Cascades to nested objects | yes (on a field) | no |
| Groups | no | yes: @Validated(OnCreate.class) |
| On a service class | meaningless | enables method validation |
In the service layer:
@Service
@Validated
class TransferService {
void transfer(@NotNull Long from, @Positive BigDecimal amount) { ... }
}
For this Spring creates a proxy, and on a violation you get ConstraintViolationException. In a controller, if the body is invalid you get MethodArgumentNotValidException instead, and you need to catch the two separately in a @RestControllerAdvice.
Don't forget: if spring-boot-starter-validation isn't added, the annotations are silently ignored.
Sign up to mark studied questions and save your progress.