Consider a Spring Boot REST controller method annotated with @Valid on a request body. What is the default behavior when the input fails validation?
public record UserRequest(@NotBlank String name, @Min(18) int age) {} @PostMapping("/users") public ResponseEntity<String> createUser(@Valid @RequestBody UserRequest user) { return ResponseEntity.ok("User created"); }
Think about how Spring Boot handles validation exceptions by default.
When @Valid detects invalid input, Spring Boot triggers a validation exception before the controller method executes. This results in a 400 Bad Request response with details about the validation errors.
Choose the code snippet that correctly uses validation annotations on a Spring Boot record used as a request DTO.
Remember which annotations apply to which data types.
@NotEmpty and @NotBlank apply to Strings or collections, while @Positive and @Min apply to numbers. Option D correctly applies @NotEmpty to a String and @Positive to an int.
Given the controller method below, why might validation errors not trigger a 400 response?
public record OrderRequest(@NotNull String productId, @Min(1) int quantity) {} @PostMapping("/orders") public ResponseEntity<String> placeOrder(OrderRequest order) { return ResponseEntity.ok("Order placed"); }
Think about how Spring binds HTTP request data to method parameters.
Without @RequestBody, Spring does not deserialize the JSON request body into the OrderRequest object, so validation annotations are not processed. Adding @RequestBody and @Valid triggers validation.
Given the controller method below, what is the HTTP status code and response body when the client sends {"name":"", "age":15}?
public record UserRequest(@NotBlank String name, @Min(18) int age) {} @PostMapping("/users") public ResponseEntity<String> createUser(@Valid @RequestBody UserRequest user) { return ResponseEntity.ok("User created"); }
Recall the default error response Spring Boot sends on validation failure.
Spring Boot returns a 400 Bad Request with a JSON body describing each validation error, including that 'name' must not be blank and 'age' must be at least 18.
Which approach allows you to globally customize the JSON structure returned when validation errors occur in a Spring Boot REST API?
Think about how Spring Boot handles exceptions globally.
Using a @ControllerAdvice with an @ExceptionHandler for MethodArgumentNotValidException lets you intercept validation errors globally and customize the JSON response structure.