🎯 What you will learn
Bean Validation (Jakarta Validation API) lets you declare constraints directly on your DTO fields — then a single @Valid annotation on the controller parameter tells Spring to enforce them before your method body runs. By the end of this lesson you will understand:
- Declaring Java records as immutable, self-documenting request DTOs
- Constraint annotations:
@NotBlank,@Positive,@Max,@Pattern - Triggering validation with
@Valid @RequestBody - The automatic 400 Bad Request Spring returns when constraints fail
- Returning structured error bodies with
@RestControllerAdvice(Lesson 23) - Response DTOs as records — no validation needed on output shapes
@NotNull, @NotEmpty, and @NotBlank — and why you pair @Valid with @RequestBody — immediately signals senior-level fluency.
🌍 Real-world scenario
NairaSwift receives malformed POST bodies — missing sender accounts, negative amounts, wrong currency codes. Samuel adds Bean Validation so those requests are rejected with clear 400 messages before they reach the service layer, never polluting the ledger.
📦 Block 1 — DTO record with constraints
A Java record makes the perfect immutable DTO: constructor, getters, equals, hashCode, and toString are all auto-generated. Constraint annotations on record components work identically to regular class fields.
Why records? A DTO record in one line replaces 30+ lines of boilerplate. The record components are effectively final, which prevents accidental mutation of incoming data anywhere in the request lifecycle.
✅ Block 2 — @Valid in controller + valid request
@Valid is the switch that activates constraint checking. Without it, Spring passes the deserialized object to your method regardless of its field values. With it, Spring runs the validator first — failures throw MethodArgumentNotValidException and return 400 automatically.
🚫 Block 3 — Invalid request → structured 400
When @Valid detects constraint violations, Spring collects all failures (not just the first) and throws MethodArgumentNotValidException. A @RestControllerAdvice handler (Lesson 23) formats them into a structured JSON body so mobile clients can display each field error individually.
All violations at once: Spring collects every constraint failure before responding. This means the client gets a complete list of what to fix — not a frustrating one-error-at-a-time loop.
📋 Common constraint annotations
| Annotation | What it checks | Works on |
|---|---|---|
@NotNull | Value must not be null | Any |
@NotEmpty | Not null and not empty (length > 0) | String, Collection |
@NotBlank | Not null, not empty, not whitespace-only | String |
@Positive | Strictly > 0 | Numeric |
@PositiveOrZero | >= 0 | Numeric |
@Min(n) / @Max(n) | Value within bounds | Numeric |
@Pattern(regexp) | Matches regex | String |
@Email | Valid email format | String |
@Size(min,max) | Length / size within bounds | String, Collection |
🎤 Interview Q&A
@NotNull: value must not be null. @NotEmpty: not null and not empty (for Strings/Collections). @NotBlank: not null, not empty, and not whitespace-only. Use @NotBlank for user-facing String inputs.
spring-boot-starter-validation includes Hibernate Validator, the reference implementation. Add it to pom.xml and the javax/jakarta validation annotations become available.
Annotate the nested field with @Valid. For example, if TransferRequest has a nested Address field, annotate it @Valid Address billingAddress so Address's constraints are also checked.
Create a @Constraint annotation and a ConstraintValidator<A,T> implementation. The isValid() method receives the value and a ConstraintValidatorContext. Compose your business rule and return true/false.
When @Valid is present, Spring's MethodValidationInterceptor (or WebDataBinder for @RequestBody) calls the ValidatorFactory to obtain a Validator and invokes validate(). Violations are collected into BindingResult; if any exist and BindingResult is not in the method signature Spring throws MethodArgumentNotValidException, which propagates to exception handlers.
📝 Quiz — 5 questions
Next: Error Handling and ResponseEntity →
⚠️ Common mistakes
✅ Key takeaways
- spring-boot-starter-validation adds Jakarta Bean Validation via Hibernate Validator
- Record DTOs + constraint annotations = concise, self-documenting input contracts
- @Valid on @RequestBody triggers constraint checking; failures → 400 automatically
- @NotBlank, @Positive, @Pattern, @Max cover the vast majority of field-level rules
- Custom @Constraint annotations handle domain-specific rules (e.g., IBAN format)
Validate inputs. Ship safe APIs.
Join the Best AI Programs — three 5-month courses, fully online, with placement assistance. Week 1 is free.
Explore our AI-era courses →