@Valid校验
@RestController @RequestMapping("/test") public class TRestController{ //接口参数校验
@PostMapping("add") public ApiResponse add(@RequestBody @Valid User user){ ........... } } //接收参数对象,校验入参 @Data public class User{ @NotNull(message = "不能为空") //校验规则 private Long id; ...... @Valid //嵌套校验 private UserData userData; }
@Validated校验基本类型入参
@RestController @RequestMapping("/test") @Validated //表示注解校验生效 public class TRestController{ //接口参数校验 //@NotNull 用于校验方法参数 @PostMapping("add") public ApiResponse add( @RequestParam @NotNull(message="不能为空") String userName){ ........... } }
@Validated分组校验
@RestController @RequestMapping("/test") public class TRestController{ //接口参数校验 //@Validated(Add.class) Add分组参数校验 @PostMapping("add") public ApiResponse add( @RequestParam @Validated(Add.class) User user){ ........... } //@Validated(Update.class) Update分组参数校验 @PostMapping("update") public ApiResponse update( @RequestParam @Validated(Update.class) User user){ ........... } } public class User{ @NotNull(message="不能为空",groups={Add.class,Update.class}) private String name; ....... } // 定义校验分组 public interface Add{} // 定义校验分组 public interface Update{}
自定义注解校验
//定义注解 @Target({ElementType.METHOD,ElementType.FIELD,ElementType.ANNOTATION_TYPE}) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = EnumCheckValidator.class) public @interface EnumCheck { String message() default ""; Class<?>[] groups() default { }; Class<? extends Payload>[] payload() default { }; Class<? extends Enum<?>> enumClass(); String enumMethod(); } //自定义校验规则类 public class EnumCheckValidator implements ConstraintValidator<EnumCheck,String> { @Override public void initialize(EnumCheck enumCheck) {//初始化方法 ....... } @Override public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) { //实现校验规则 ...... } } //自定义注解使用 public class User{ @EnumCheck(message="",......) private String userName; ...... }
标签:String,校验,class,add,Valid,Validated,public From: https://www.cnblogs.com/in-here/p/16775071.html