The 30 second answer
I add spring-boot-starter-validation, put Bean Validation annotations like @NotBlank, @Email, @Positive and @Size on the request DTO fields, and mark the controller parameter with @Valid. If validation fails, Spring throws MethodArgumentNotValidException and returns 400 before my code runs. I turn that into a clear error list in my @RestControllerAdvice. Business rules that need the database stay in the service.
<!-- level: 1 --> <!-- must_know: true -->
public record CreateOrderRequest(
@NotBlank String customerId,
@NotEmpty List<@Valid OrderLine> lines,
@Email String receiptEmail) { }
public record OrderLine(@NotBlank String sku, @Positive int quantity) { }
@PostMapping
public OrderDto create(@Valid @RequestBody CreateOrderRequest request) { ... }- Spring Boot validation is based on Bean Validation (Jakarta Validation) with Hibernate Validator, which
spring-boot-starter-validationbrings in. Without it on the classpath, the annotations do nothing. @Valid(or Spring's@Validated) on a@RequestBodyparameter triggers validation; a failure raisesMethodArgumentNotValidException, which Spring MVC maps to400 Bad Request.@Validatedon a class enables method validation, for example for@RequestParam @Min(1) int page.- Validation checks the shape of input. Rules such as "the product exists" or "the customer has enough credit" belong in the service layer.
Sources (2)
- Spring Boot reference: Validationdocs.spring.io
- Spring Framework: MVC validationdocs.spring.io