<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
public class Order {
@NotNull
private String orderId;
@DecimalMin("0")
private BigDecimal amount;
// getters and setters
}
@PostMapping("/orders")
public ResponseEntity<String> createOrder(@Valid @RequestBody Order order) {
// ...
}
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<String> handleValidationException(MethodArgumentNotValidException ex) {
BindingResult result = ex.getBindingResult();
List<String> errors = result.getFieldErrors().stream()
.map(error -> error.getField() + ": " + error.getDefaultMessage())
.collect(Collectors.toList());
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errors.toString());
}
}