Spring / Spring Boot 4 Basics Interview Questions
How does Bean Validation work with Spring Boot 4?
Spring Boot 4 auto-configures Jakarta Bean Validation 3.1 when spring-boot-starter-validation is on the classpath. Validation annotations on request bodies, path variables, and method parameters are enforced automatically.
// DTO with validation constraints: public record CreateOrderRequest( @NotBlank(message = "Product ID is required") String productId, @Min(value = 1, message = "Quantity must be at least 1") @Max(value = 100, message = "Quantity cannot exceed 100") int quantity, @Email(message = "Invalid email address") @NotNull String customerEmail, @NotNull @Valid // cascade validation into nested object AddressRequest shippingAddress ) {} public record AddressRequest( @NotBlank String line1, @Nullable String line2, @NotBlank @Size(min=5, max=10) String postcode ) {} // Controller: @Valid triggers validation before method body: @PostMapping @ResponseStatus(HttpStatus.CREATED) public OrderDto createOrder(@Valid @RequestBody CreateOrderRequest request) { return service.create(request); } // Handle validation errors globally: @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public Map<String, String> handleValidation(MethodArgumentNotValidException ex) { Map<String, String> errors = new LinkedHashMap<>(); ex.getBindingResult().getFieldErrors() .forEach(err -> errors.put(err.getField(), err.getDefaultMessage())); return errors; } } // Service-level validation with @Validated: @Service @Validated // enables method-level validation public class OrderService { public Order getOrder(@NotBlank String id) { return repo.findById(id).orElseThrow(); } }
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
