如何从类级别注释违规中获取属性路径

时间:2011-06-09 16:58:27

标签: java hibernate bean-validation hibernate-validator

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

这是我的注释实现 -

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

1 个答案:

答案 0 :(得分:2)

您需要将消息设置为映射到执行验证时要拒绝的属性。 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;
    }
  }
}