自定义校验注解

需求原型是

许多接口都需要 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

 

posted @ 2020-11-30 19:54  byebai95  阅读(223)  评论(0编辑  收藏  举报