美文网首页
2020-06-25

2020-06-25

作者: 多走走多看看 | 来源:发表于2020-09-20 21:23 被阅读0次

    自定义注解(参数类型校验)

    public class FlagValidatorClass implements ConstraintValidator<FlagValidator,Integer> {
        private String[] values;
        @Override
        public void initialize(FlagValidator constraintAnnotation) {
            values = constraintAnnotation.value();
        }
    
        @Override
        public boolean isValid(Integer value, ConstraintValidatorContext context) {
            boolean isValid = false;
            if(value == null){
                return false;
            }
            for (int i = 0; i < values.length; i++) {
                if(values[i].equals(String.valueOf(value))){
                    isValid = true;
                    break;
                }
            }
            return isValid;
        }
    }
    
    @Documented
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.FIELD,ElementType.PARAMETER})
    @Constraint(validatedBy =  FlagValidatorClass.class)
    public @interface FlagValidator {
        String[] value() default {};
        String message() default "flag is not found";
        Class<?>[] groups() default {};
        Class<? extends Payload>[] payload() default {};
    }
    
    @FlagValidator(value = {"0","1"},message = "请求类型不正确")
    private Integer requireType;
    

    相关文章

      网友评论

          本文标题:2020-06-25

          本文链接:https://www.haomeiwen.com/subject/mtcsfktx.html