从自定义约束中引用其他 bean 值

Referencing other bean values from within custom constraint

我正在为我的项目使用 Hibernate Validator。我想使用自定义约束从约束验证器实现中的 bean 引用另一个字段。这怎么可能?

豆子

@NotNull(when="mvel:this.two == null")
private String one;

@NotNull(when="mvel:this.one == null")
private String two;

验证者

public class NotNullValidator implements ConstraintValidator<NotNull, String> {

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        //how do I get access to the parent bean here??
    }
}

我正在使用 Hibernate 5.0.0,Jersey 2.6,JBoss 5,Java 6.

简短的回答是你不能。可用于字段验证的当前上下文信息不允许您访问整个 bean 实例。至少现在不是。有关于将根 bean 添加到上下文的讨论,但根据 Bean 验证规范,根 bean 不可用。这背后的原因是 Validator 的某些方法没有 bean 实例 (validateValue)。根据使用的验证方法,约束可能会通过或失败。

如果您想 compare/reference 多个字段,您将需要自定义 class 级别约束。