当约束仅在父 class 中时跳过验证

Validation is skipped when constraints are only in parent class

我使用 MOXy 作为 JAXB 提供程序以及 Bean 验证。

我正在尝试验证 class,其中只有父字段带有约束注释。

我可以看到 MOXy 正在跳过此 class 的验证,可能它没有查看父级 class。

你能告诉我如何克服这个问题吗?

这是 2.6.0 中的一个已知问题。它已在 master (2.7.x) 中修复,将被移植到 2.6.2,不计划移植到 2.6.1。不幸的是,这些构建还不适用于 public。您应该等待 2-3 个月。

作为解决方法,我建议将 BV 注释从超类移动到所有子类。是的,我同意它很丑。 :(

我找到了一个快速解决方法。它是关于创建将始终通过的虚拟约束。然后你可以把它放在任何 class 上。 MOXy 将打开验证。

虚拟约束:

@Target( {ElementType.CONSTRUCTOR})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = PutItWhenYouDoNotHaveConstraintsButParentHas.Validator.class)
@Documented
public @interface  PutItWhenYouDoNotHaveConstraintsButParentHas {

    String message() default "{com.mycompany.constraints.checkcase}";
    Class<? extends Payload>[] payload() default {};
    Class<?>[] groups() default {};
    public static class Validator implements ConstraintValidator<PutItWhenYouDoNotHaveConstraintsButParentHas, Object>{

        @Override
        public void initialize(PutItWhenYouDoNotHaveConstraintsButParentHas constraintAnnotation) {

        }

        @Override
        public boolean isValid(Object value, ConstraintValidatorContext context) {
            return true;
        }
    }
}

用法示例:

public class IdoNotHaveConstraints extends ButMyParentHas{

    @PutItWhenYouDoNotHaveConstraintsButParentHas
    public IdoNotHaveConstraints (){

    }
}