annotation+reflectino+constraint实现字段校验 封装需准备如下:
字段的注解:合法的参数值,提示信息,分组,payload字段校验类:对参数进行校验,是否在规定的参数值中实体类:用户实体类,对sex字段加自定义注解controller类:@Valid或@Validated,进行测试代码示例:
/** * 自定义字段校验注解 */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = FieldCheckConstraint.class) public @interface FieldCheck { // 合法的参数值 String[] paramValues(); // 提示信息 String message() default "参数不正确"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; } public class FieldCheckConstraint implements ConstraintValidator<FieldCheck,Object> { // 从注解中获取合法的参数值 private List<String> paramValues; @Override public void initialize(FieldCheck constraintAnnotation) { // 初始化时获取注解上的参数值 paramValues = Arrays.asList(constraintAnnotation.paramValues()); } @Override public boolean isValid(Object o, ConstraintValidatorContext constraintValidatorContext) { if (paramValues.contains(o)) { return true; } // 若不在参数值中则false return false; } } public class User implements Serializable { private static final long serialVersionUID = 1L; private String id; private String name; @FieldCheck(paramValues = {"girl","boy","secret"},message = "参数未在规定参数枚举中") private String sex; } @RequestMapping("/hello") public Object hello(@Valid @RequestBody User user) { user.getSex(); return "已通过字段校验,顺利进入该方法"; } @RequestMapping("/hello2") public Object hello2(@RequestBody User user) { return "已通过字段校验,顺利进入该方法"; }已测试,符合预期 小结:注解的应用范围,通过注解对指定字段进行校验,需强化练习注解+反射的使用