1

我正在使用休眠验证器。我有一个类级别的注释。它比较三个属性的相等性。执行验证时,我需要从返回的 javax.validation.ConstraintViolation 对象中获取 PropertyPaths。由于它不是单个字段,因此 getPropertyPath() 方法返回 null。还有其他方法可以找到 PropertyPaths 吗?

这是我的注释实现 -

@MatchField.List({
@MatchField(firstField = "firstAnswer", secondField = "secondAnswer", thirdField = "thirdAnswer"),
})
4

1 回答 1

3

您需要将消息设置为在进行验证时映射到您希望拒绝的属性。Hibernate Validator 无法自动神奇地找出自定义注释属性是属性路径。

public class MatchFieldValidator implements ConstraintValidator<MatchField, Object> {

  private MatchField matchField;

  @Override
  public void initialize(MatchField matchField) {
    this.matchField = matchField;
  }

  @Override
  public boolean isValid(Object obj, ConstraintValidatorContext cvc) {

    //do whatever you do
    if (validationFails) {
      cvc.buildConstraintViolationWithTemplate("YOUR FIRST ANSWER INPUT IS WRONG!!!").
                        addNode(matchField.firstAnswer()).addConstraintViolation();
      cvc.buildConstraintViolationWithTemplate("YOUR SECOND ANSWER INPUT IS WRONG!!!").
                        addNode(matchField.secondAnswer()).addConstraintViolation();
      //you get the idea
      cvc.disableDefaultConstraintViolation();
      return false;
    }
  }
}
于 2011-06-09T18:48:50.700 回答