zoukankan      html  css  js  c++  java
  • 自定义校验注解

    需求原型是

    许多接口都需要 userId 作为参数,参与接口的调用,但是很多情况下,传入不存在的userId 到数据库,会产生脏数据,因此需要在接口接收userId 的时候校验用户表是否存在此 userId

    第一步:自定义注解 CheckUser

    @Target({ElementType.PARAMETER,ElementType.FIELD,ElementType.METHOD})
    @Retention(RetentionPolicy.RUNTIME)
    @Constraint(validatedBy = CheckUserImpl.class)
    public @interface CheckUser {
    
        /**
         * 是否允许为空
         *
         * @return
         */
        boolean allowNull() default false;
    
        /**
         * 是否需要校验(如果单纯只是想作为swagger提示展示的时候就设置为false)
         *
         * @return
         */
        boolean doValid() default true;
    
        /**
         * 提示信息
         *
         * @return
         */
        String message() default "用户id不存在";
    
        Class<?>[] groups() default {};
    
        Class<? extends Payload>[] payload() default {};
    
        /**
         * 是否隐藏参数
         *
         * @return
         */
        boolean hideDescription() default false;
    }

    第二步:编写注解的实现类 CheckUserImpl

    @Slf4j
    @Aspect
    @Component
    public class CheckUserImpl implements ConstraintValidator<CheckUser,Long> {
    
        private CheckUser constraintAnnotation;
        @Autowired
        private ValidateDao validDao;
    
    
        @Override
        public boolean isValid(Long value, ConstraintValidatorContext context) {
            if (value == null || value == 0) {
                return constraintAnnotation.allowNull();
            }
            boolean doValid = this.constraintAnnotation.doValid();
            if (!doValid) {
                return true;
            }
            Integer result = validDao.validUserId(value);
            if(result >0){
                return true;
            }
            return false;
        }
    
        @Override
        public void initialize(CheckUser constraintAnnotation) {
            this.constraintAnnotation = constraintAnnotation;
        }
    }

    在实现类中,ValidateDao 为 mybatis 提供的接口

    第三步:在参数处指定需要校验的 UserId

  • 相关阅读:
    算法之路 level 01 problem set
    算法原理与实践(链表)
    散列表(HashTable)
    系统设计与实践(实战演练)
    桶排序 + 基数排序
    算法原理与实践(二叉树)
    Total Difference String
    【翻译】std::list::remove
    【翻译】std::remove
    Observer模式实践
  • 原文地址:https://www.cnblogs.com/bytecodebuffer/p/14063235.html
Copyright © 2011-2022 走看看