What is @Valid and Bean Validation in Spring Boot?
Why Interviewers Ask This
Interviewers use this question to quickly assess whether a candidate has the foundational knowledge required for Spring Boot development. It reveals whether you understand the building blocks that more complex concepts rely on.
Answer
Bean Validation (JSR-380) with Hibernate Validator provides declarative validation for Java beans. Spring Boot integrates it with spring-boot-starter-validation. Constraint annotations on entity/DTO fields: public class CreateUserRequest { @NotBlank(message = "Name is required") @Size(min = 2, max = 50) private String name; @NotBlank @Email(message = "Invalid email format") private String email; @NotNull @Min(18) @Max(120) private Integer age; @NotNull @Pattern(regexp = "^\d{10}$", message = "Must be 10 digits") private String phone; @Future private LocalDate expiryDate; @NotEmpty private List<@Valid AddressDTO> addresses; }. Triggering validation: add @Valid or @Validated to controller parameters: @PostMapping public ResponseEntity<User> createUser(@Valid @RequestBody CreateUserRequest request) { ... }. Spring automatically validates and returns 400 with error details if validation fails. Handling validation errors: @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<Map<String,String>> handleValidation(MethodArgumentNotValidException ex) { Map<String,String> errors = new HashMap<>(); ex.getBindingResult().getFieldErrors().forEach(e -> errors.put(e.getField(), e.getDefaultMessage())); return ResponseEntity.badRequest().body(errors); }. Custom validators: implement ConstraintValidator interface for custom business rules. Groups: validate different constraints for different scenarios (Create group vs Update group) using validation groups.
Common Mistake
Candidates often give textbook answers here. Interviewers are more impressed when you relate the concept to a specific problem you solved in a real Spring Boot project.