Easy java spring

How do you validate request input in Spring Boot?

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-validation brings in. Without it on the classpath, the annotations do nothing.
  • @Valid (or Spring's @Validated) on a @RequestBody parameter triggers validation; a failure raises MethodArgumentNotValidException, which Spring MVC maps to 400 Bad Request.
  • @Validated on 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)
  1. Spring Boot reference: Validationdocs.spring.io
  2. Spring Framework: MVC validationdocs.spring.io