Skip to main content
PreparationZone Logo
PrepZone

Bean Validation in Practice

@Valid, built-in constraints, custom validators and validation groups.

Pass checkpoint below

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 · Fresher

Annotate request DTOs with @NotNull, @Size, etc., and add @Valid on the controller parameter to trigger validation before business logic.

Bean Validation 3.x

L2 · Intermediate

Hibernate Validator implements Jakarta Validation annotations. Custom constraints implement ConstraintValidator for BookStore-specific rules.

Validation groups

L3 · Advanced

Use 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.

ApplicationContext
BookController@RestController
BookService@Service
BookRepository@Repository
DataSourceAuto-configured

Arrows show @Autowired wiring — container injects at startup

The ApplicationContext reads configuration, creates beans, and wires dependencies automatically.

Enable validation

Add the validation starter:

Java
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

Annotate the controller parameter:

Java
@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.