<dependencies>
</dependencies>
public interface AddGroup {
}
/**
* 校验分组 edit
*/
public interface EditGroup {
}
/**
* 校验分组 query
*/
public interface QueryGroup {
}
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ValidatorUtils {
private static final Validator VALID = SpringUtil.getBean(Validator.class);
public static <T> void validate(T object,Class<?>... groups) {
Set<ConstraintViolation<T>> validate = VALID.validate(object,groups);
if (!validate.isEmpty()){
throw new ConstraintViolationException("参数校验异常", validate);
}
}
}
@Data
public class TestDemoBo {
/**
* 主键
*/
@NotNull(message = "主键不能为空", groups = {EditGroup.class})
private Long id;
/**
* 部门id
*/
@NotNull(message = "部门id不能为空", groups = {AddGroup.class, EditGroup.class})
private Long deptId;
/**
* 用户id
*/
@NotNull(message = "用户id不能为空", groups = {AddGroup.class, EditGroup.class})
private Long userId;
/**
* 排序号
*/
@NotNull(message = "排序号不能为空", groups = {AddGroup.class, EditGroup.class})
private Integer orderNum;
/**
* key键
*/
@NotBlank(message = "key键不能为空", groups = {AddGroup.class, EditGroup.class})
private String testKey;
/**
* 值
*/
@NotBlank(message = "值不能为空", groups = {AddGroup.class, EditGroup.class})
private String value;
}
@RestController
@RequestMapping("/validator")
public class ValidatorController {
@PostMapping("/add")
public Dict add(@RequestBody TestDemoBo bo) {
// 使用校验工具校验 @Validated(AddGroup.class) 注解
// 用于非 controller 的地方校验对象
ValidatorUtils.validate(bo, AddGroup.class);
return Dict.create().set("msg", "success");
}
@PutMapping("/edit")
public Dict edit(@Validated(EditGroup.class) @RequestBody TestDemoBo bo){
return Dict.create().set("msg", "success");
}
}
优雅进行字段校验
参数校验
@Validated 和 @Valid 的区别