Bean Validation
bean validation jakarta bean validation (@notnull, @size, @email) declaratively validates request dtos. spring boot auto-configures hibernate validator — just annotate your fields
Introduction
Jakarta Bean Validation (@NotNull, @Size, @Email) declaratively validates request DTOs. Spring Boot auto-configures Hibernate Validator — just annotate your fields and use @Valid on controller parameters.
Informative example
DTO validation in a REST controller:
public record CreateUserRequest(@NotBlank @Size(min = 2, max = 50) String name,@NotBlank @Email String email,@NotNull @Min(18) Integer age) {}@PostMapping("/users")public ResponseEntity<User> create(@Valid @RequestBody CreateUserRequest req) {return ResponseEntity.ok(service.create(req));}// Custom validator@Constraint(validatedBy = UniqueEmailValidator.class)@interface UniqueEmail {}@UniqueEmail String email;
Best practices
- Validate at the boundary (controller) — don't trust client input.
- Return 400 with field-level errors via @ControllerAdvice + MethodArgumentNotValidException.
- Use groups for different validation rules (create vs update).
Purpose of this lesson
Master Bean Validation so you can apply it confidently in production Java code, technical interviews, and code reviews.
Step-by-step explanation
- Understand the core idea behind Bean Validation.
- Walk through the runnable example and tweak it in the playground.
- Apply the pattern in a small Spring Boot or CLI exercise of your own.
- Re-read the common mistakes and interview Q&A to lock the concept in.
Interactive workflow diagram
Identify use case
Recognize when bean validation is the right tool for the problem.
Debugging tips
- @Valid not triggering? Must be on @RequestBody parameter AND class must have constraint annotations.
Optimization strategies
- Profile before optimizing — JFR (Java Flight Recorder) and async-profiler reveal real hotspots.
- Prefer immutable data and stream pipelines over hand-rolled loops when readability matters.
- Reach for the right JDK collection (ArrayList vs LinkedList vs ArrayDeque) before writing custom data structures.
Enterprise example
Teams at Netflix, Uber and Goldman Sachs apply Bean Validation daily — usually wrapped behind Spring Boot services with observability hooks (Micrometer + OpenTelemetry).
Interview questions & answers
Q1Explain Bean Validation in one minute.
Q2When would you avoid Bean Validation?
Summary
In this lesson you learned Bean Validation — the concept, syntax, a runnable example, and the production pitfalls to avoid. Apply it in the playground before moving on.