@Validated
注解在 Spring Boot 中用于方法参数校验,通常与 @Valid
注解结合使用,确保传入的参数符合指定的约束条件。它是 Spring 对 JSR-303/JSR-380(Bean Validation)规范的扩展,支持分组校验。
1. 基本使用
1.1 添加依赖
首先,确保项目中包含 spring-boot-starter-validation
依赖:
xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
1.2 定义实体类
在实体类中使用校验注解,如 @NotNull
、@Size
等:
java
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class User {
@NotNull(message = "Name cannot be null")
private String name;
@Size(min = 1, max = 10, message = "Description must be between 1 and 10 characters")
private String description;
// Getters and Setters
}
1.3 在 Controller 中使用 @Validated
在 Controller 方法参数前使用 @Validated
或 @Valid
注解触发校验:
java
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
@RestController
@RequestMapping("/users")
@Validated
public class UserController {
@PostMapping
public String createUser(@Valid @RequestBody User user) {
return "User is valid";
}
}
2. 分组校验
@Validated
支持分组校验,适用于不同场景下的不同校验规则。
2.1 定义分组接口
创建分组接口:
java
public interface GroupA {}
public interface GroupB {}
2.2 在实体类中指定分组
在实体类中为校验注解指定分组:
java
public class User {
@NotNull(groups = GroupA.class, message = "Name cannot be null")
private String name;
@Size(groups = GroupB.class, min = 1, max = 10, message = "Description must be between 1 and 10 characters")
private String description;
// Getters and Setters
}
2.3 在 Controller 中使用分组校验
在 Controller 方法中使用 @Validated
指定分组:
java
@RestController
@RequestMapping("/users")
@Validated
public class UserController {
@PostMapping("/groupA")
public String createUserGroupA(@Validated(GroupA.class) @RequestBody User user) {
return "User is valid for GroupA";
}
@PostMapping("/groupB")
public String createUserGroupB(@Validated(GroupB.class) @RequestBody User user) {
return "User is valid for GroupB";
}
}
3. 方法级别校验
@Validated
还可用于方法级别的参数校验。
3.1 在 Service 层使用
在 Service 层方法参数前使用 @Validated
:
java
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;
@Service
@Validated
public class UserService {
public void createUser(@Valid User user) {
// 业务逻辑
}
}
4. 异常处理
校验失败时,Spring 会抛出 MethodArgumentNotValidException
或 ConstraintViolationException
,可以通过 @ControllerAdvice
或 @ExceptionHandler
捕获并处理。
java
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.HashMap;
import java.util.Map;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException.class)
public Map<String, String> handleValidationExceptions(MethodArgumentNotValidException ex) {
Map<String, String> errors = new HashMap<>();
ex.getBindingResult().getFieldErrors().forEach(error ->
errors.put(error.getField(), error.getDefaultMessage()));
return errors;
}
}
总结
@Validated
在 Spring Boot 中用于参数校验,支持分组校验和方法级别校验,结合 @Valid
使用,能有效确保数据合法性,并通过异常处理机制返回友好错误信息。