Spring Boot @Validated 中 @Pattern 注意事项:变量为 null 时 @Pattern 不生效

@Pattern 在 Spring Boot @Validated 中可能是比较常见的。

但是,我在一次学习别人的代码时发现,@Pattern 校验邮箱时,email参数不传时请求能正常通过。

然后就是我一天的时间都在找源码中的原因了。我发现 @Validated 注解在最后对 @Pattern 生效时居然使用的是org.hibernate.validator.internal.constraintvalidators.bv.PatternValidator.isValid(CharSequence value, ConstraintValidatorContext constraintValidatorContext)

hibernate 下的类!Spring Boot @Validated 依赖 MyBatis ?

下面事源码:

public boolean isValid(CharSequence value, ConstraintValidatorContext constraintValidatorContext) {
        if (value == null) {
            return true;
        } else {
            if (constraintValidatorContext instanceof HibernateConstraintValidatorContext) {
                ((HibernateConstraintValidatorContext)constraintValidatorContext.unwrap(HibernateConstraintValidatorContext.class)).addMessageParameter("regexp", this.escapedRegexp);
            }

            Matcher m = this.pattern.matcher(value);
            return m.matches();
        }
    }

 

你可能感兴趣的:(未知错误)