Bean Validation (@Valid) — Spring Technical Interview Questions & Answers
Validating request payloads with JSR-380 annotations.
Bean Validation (@Valid)
- Bean Validation checks request data before your logic runs.
- Annotations: @NotNull, @NotBlank, @Size, @Email, @Min, @Max.
- Put @Valid on the @RequestBody argument.
- Invalid data can become a 400-style error via exception handling.
- Validating only in the UI and trusting every API call.
- Validate on the server always.
Technical Interview Tip: @Valid + field annotations + 400 on failure.
Code Examples for Bean Validation (@Valid)
Bean Validation (@Valid) — working example
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
@RestControllerAdvice
class ApiErrors {
@ExceptionHandler(IllegalArgumentException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
Map<String, String> badRequest(IllegalArgumentException ex) {
return Map.of("error", ex.getMessage());
}
}
record CreateUserRequest(@NotBlank @Email String email) {}
@RestController
class Users {
@PostMapping("/users")
User create(@Valid @RequestBody CreateUserRequest req) {
return new User(req.email());
}
}Bean Validation (@Valid) — @RestControllerAdvice centralizes API errors; @Valid triggers bean validation on DTOs.
How to Explain Bean Validation (@Valid) to an Interviewer
What is Bean Validation (@Valid) (sb misc)?
Used for a short Bean Validation @Valid sb misc example a small REST app Not just the heading
Give one small example of Bean Validation (@Valid) (sb misc).
the smallest Bean Validation @Valid sb misc example you can type Validating request payloads with JSR-380 annotations
What mistake do beginners make with Bean Validation (@Valid) (sb misc)?
only saying “Bean Validation @Valid sb misc” with no example Show the fix
Where do you use Bean Validation (@Valid) (sb misc)?
a small REST app a short Bean Validation @Valid sb misc example