How to use @Validated in Spring Boot?

In Spring Boot, the @Validated annotation is used to validate the validity of method parameters. It can be applied to request handling methods in Controllers or methods in the Service layer.

The steps for using the @Validated annotation are as follows:

  1. Add the spring-boot-starter-validation dependency to the pom.xml file to include dependencies.
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>
  1. Add the @Validated annotation to Controller or Service methods.
@RestController
@Validated
public class MyController {
    @GetMapping("/validate")
    public String validate(@RequestParam("param1") @NotNull String param1, 
                           @RequestParam("param2") @Min(18) int param2) {
        // 处理请求
        return "ok";
    }
}

In the above example, @RequestParam(“param1”) @NotNull indicates that the param1 parameter cannot be null, and @RequestParam(“param2”) @Min(18) indicates that the minimum value for the param2 parameter is 18.

  1. Configure a handler for failed validation (optional): You can define a global handler to manage cases of validation failure, such as sending error messages to the client.
@ControllerAdvice
public class ValidationExceptionHandler {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ResponseEntity handleValidationExceptions(MethodArgumentNotValidException ex) {
        // 处理验证失败的情况
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Validation error");
    }
}

In the given example, @ExceptionHandler(MethodArgumentNotValidException.class) indicates that when a validation failure occurs, the handleValidationExceptions() method is called to handle it.

This way, you can use the @Validated annotation in Spring Boot to validate the validity of method parameters.

bannerAds