Why this matters
- Validation at the API boundary rejects bad data before it touches business logic or the database.
- Built-in constraints cover 90% of BookStore needs; custom validators handle domain rules like ISBN format.
- Consistent validation error responses (via
@ControllerAdvice) improve client developer experience.
@Valid on input
L1 · FresherAnnotate request DTOs with @NotNull, @Size, etc., and add @Valid on the controller parameter to trigger validation before business logic.
Bean Validation 3.x
L2 · IntermediateHibernate Validator implements Jakarta Validation annotations. Custom constraints implement ConstraintValidator for BookStore-specific rules.
Validation groups
L3 · AdvancedUse groups for create vs update flows so the same DTO enforces different rules on POST and PATCH.
Method-level validation
L4 · Expert@Validated on services enables @NotNull on method parameters — keep web validation at the edge and domain rules in services.
Arrows show @Autowired wiring — container injects at startup
Enable validation
Add the validation starter:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
Annotate the controller parameter:
@PostMapping
public BookResponse create(@RequestBody @Valid CreateBookRequest request) {
return BookResponse.from(bookService.create(request));
}
@Valid triggers validation before the method body executes.
The rest of this guide is part of Pro
Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.
Still to come · 6 sections
- Built-in constraints on DTOs
- Path variable and query param validation
- Custom validator
- Validation groups
- Error response format
- Programmatic validation
Test yourself
Answer these before moving on — recall is what makes it stick.