How does validation work in Spring Boot with @Valid and Bean Validation?
Learn how @Valid and Bean Validation work in Spring Boot, from field constraints and Hibernate Validator to handling errors with @ControllerAdvice.
Expected Interview Answer
Spring Boot validates request data by combining the @Valid (or @Validated) annotation with Bean Validation constraints such as @NotNull, @Size, and @Email declared on the target object's fields.
When a controller parameter annotated with @Valid is bound, Spring triggers the Jakarta Bean Validation provider — Hibernate Validator by default — to check every constraint. On a @RequestBody a failure throws MethodArgumentNotValidException; on a form-bound object errors collect in a BindingResult. A @ControllerAdvice with @ExceptionHandler then converts these into clean HTTP 400 responses, and @Validated on the class enables method-level and group validation.
- Declarative constraints keep validation rules on the model
- Automatic 400 responses on invalid input
- Reusable across controllers, services, and custom validators
- Supports groups for context-specific rules
- Custom constraints via ConstraintValidator for complex logic
AI Mentor Explanation
Before a match, umpires inspect every bat against the size and edge regulations and reject any that fails. Bean Validation constraints are those regulations printed on the equipment, and @Valid is the umpire's pre-match inspection that stops an illegal bat from ever reaching the crease.
Step-by-Step Explanation
Step 1
Add the starter
Include spring-boot-starter-validation so Hibernate Validator is on the classpath.
Step 2
Annotate the model
Place constraints like @NotBlank, @Size, @Email, and @Min on the DTO fields.
Step 3
Trigger validation
Add @Valid before the @RequestBody or @ModelAttribute parameter in the controller method.
Step 4
Handle failures
Add a @ControllerAdvice with @ExceptionHandler(MethodArgumentNotValidException.class) returning a 400 with field errors.
Step 5
Enable advanced rules
Use @Validated on the class for group validation and method-level constraints on service parameters.
What Interviewer Expects
- Knows @Valid triggers Jakarta Bean Validation
- Can name common constraints and Hibernate Validator as the default
- Understands MethodArgumentNotValidException vs BindingResult
- Aware of @ControllerAdvice for centralized error handling
- Knows the difference between @Valid and @Validated groups
Common Mistakes
- Forgetting the spring-boot-starter-validation dependency
- Adding constraints but omitting @Valid so nothing runs
- Confusing @Valid (JSR standard) with @Validated (Spring, supports groups)
- Not handling MethodArgumentNotValidException, leaking stack traces
- Putting a BindingResult parameter in the wrong position relative to @Valid
Best Answer (HR Friendly)
“Spring Boot checks that incoming data follows the rules you attach to your model, like a field being required or an email being properly formatted. You mark the input with @Valid and the framework runs those checks automatically, rejecting bad requests with a helpful error instead of letting broken data through.”
Code Example
public class UserRequest {
@NotBlank
private String name;
@Email
@NotBlank
private String email;
@Min(18)
private int age;
// getters and setters
}
@RestController
@RequestMapping("/api/users")
public class UserController {
@PostMapping
public User create(@Valid @RequestBody UserRequest request) {
return userService.save(request);
}
}@RestControllerAdvice
public class ValidationAdvice {
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Map<String, String> handle(MethodArgumentNotValidException ex) {
Map<String, String> errors = new HashMap<>();
ex.getBindingResult().getFieldErrors()
.forEach(e -> errors.put(e.getField(), e.getDefaultMessage()));
return errors;
}
}Follow-up Questions
- What is the difference between @Valid and @Validated?
- How do you write a custom constraint with ConstraintValidator?
- How does validation error handling differ for @RequestBody vs form binding?
- What are validation groups and when would you use them?
- Which dependency brings Hibernate Validator into a Spring Boot app?
MCQ Practice
1. Which annotation triggers Bean Validation on a @RequestBody parameter?
@Valid on the parameter tells Spring to run the Bean Validation constraints on the bound object.
2. What exception is thrown when a @Valid @RequestBody fails validation?
For @RequestBody, a failed @Valid raises MethodArgumentNotValidException, typically mapped to HTTP 400.
3. Which is the default Bean Validation provider in Spring Boot?
Spring Boot's validation starter bundles Hibernate Validator as the reference implementation.
Flash Cards
What does @Valid do? — Triggers Jakarta Bean Validation on the annotated object so its field constraints are checked.
Default validation provider in Spring Boot? — Hibernate Validator, pulled in by spring-boot-starter-validation.
Exception for a failed @Valid @RequestBody? — MethodArgumentNotValidException, usually mapped to an HTTP 400.
@Valid vs @Validated? — @Valid is the JSR standard; @Validated is Spring's variant that adds validation groups and method-level validation.
How to centralize validation errors? — Use @RestControllerAdvice with @ExceptionHandler to convert exceptions into clean 400 responses.
Continue Learning
Related Interview Questions
What is @RequestMapping and what are its HTTP-method shortcut annotations?
easy
What is the difference between @RequestParam, @PathVariable, and @RequestBody?
medium
What is Spring Boot and how does it differ from the Spring Framework?
easy
Two users update the same record concurrently — how do you handle it with optimistic locking in Spring Data JPA?
hard