在更新表和添加数据时,为了验证不同的字段,需要做出不同的验证,so.... , Spring Boot 中,使用 Validator 分组校验可以根据不同的场景对参数进行不同的校验。以下是一个简单的分组校验实例。
1. 定义分组接口
首先,定义分组接口:
public interface CreateGroup {}
public interface UpdateGroup {}
2. 创建实体类并使用分组注解
在实体类中,使用 @Validated 注解指定分组:
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class User {
@NotNull(message = "用户名不能为空", groups = CreateGroup.class)
@Size(min = 2, max = 30, message = "用户名长度必须在{min}到{max}之间", groups = {CreateGroup.class, UpdateGroup.class})
private String name;
@NotNull(message = "年龄不能为空", groups = CreateGroup.class)
private Integer age;
// getters and setters
}
3. 创建控制器
在控制器中,根据不同的请求类型使用不同的分组进行校验:
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/users")
public class UserController {
@PostMapping
public String createUser(@RequestBody @Validated(CreateGroup.class) User user) {
return "用户创建成功!";
}
@PutMapping
public String updateUser(@RequestBody @Validated(UpdateGroup.class) User user) {
return "用户更新成功!";
}
}
4. 测试分组校验
可以使用 Postman 或其他工具测试创建和更新请求:
创建用户请求
POST /api/users
Content-Type: application/json
{
"name": "John",
"age": 25
}
更新用户请求
PUT /api/users
Content-Type: application/json
{
"name": "A",
"age": 30
}
5. 处理校验异常
使用 @ControllerAdvice 处理校验异常:
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import java.util.HashMap;
import java.util.Map;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Map<String, String>> handleValidationException(MethodArgumentNotValidException ex) {
Map<String, String> errors = new HashMap<>();
ex.getBindingResult().getAllErrors().forEach(error -> {
String fieldName = ((FieldError) error).getField();
String errorMessage = error.getDefaultMessage();
errors.put(fieldName, errorMessage);
});
return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
}
}
小结
通过以上步骤,你可以在 Spring Boot 中实现 Validator 的分组校验。根据不同的请求类型,应用不同的校验规则,使得数据验证更加灵活。