web layer
Validation with @Valid
Reject invalid requests at the boundary using Bean Validation annotations — before they reach your business logic.
Validation is about rejecting bad input at the edge of the system, before it can corrupt state or trigger obscure failures deep in the business logic. Spring integrates the Bean Validation standard (Jakarta Validation, implemented by Hibernate Validator) so that the rules live as declarative annotations on the request object itself, keeping the controller free of repetitive manual checks.
A bouncer at the door checking IDs — only valid requests get into the venue.
Key Concepts
1
You annotate fields of a DTO with constraints — @NotNull, @NotBlank, @Size(min, max), @Email, @Min/@Max, @Pattern — and then place @Valid on the corresponding @RequestBody parameter. When the request arrives, Spring runs the validator before your method body executes; if any constraint fails, it throws a MethodArgumentNotValidException and the method never runs with invalid data. You can compose constraints, validate nested objects by marking the field @Valid, and define custom constraints by writing an annotation plus a ConstraintValidator when the built-ins don't cover a domain rule. Validating at the boundary means the rest of the stack can assume well-formed input.
@NotNull@NotBlank@Size(min, max)@Email@Min
2
The piece that ties it together — and that interviews expect you to mention — is turning validation failures into a clean client response. By default the exception yields a generic 400, so you pair validation with a @RestControllerAdvice handler for MethodArgumentNotValidException that extracts the field errors and returns a structured 400 body listing each invalid field and message. It is also worth knowing the difference between @Valid (the standard, supports nested validation) and Spring's @Validated (adds validation groups for conditionally applying subsets of rules), and that validation belongs at the API boundary rather than scattered through service methods.
@RestControllerAdviceMethodArgumentNotValidException@Valid@Validated