【问题标题】:How do you get the Property Paths from a Class level Annotation violation如何从类级别注释违规中获取属性路径
【发布时间】:2011-06-09 16:58:26
【问题描述】:

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

这是我的注解实现 -

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

【问题讨论】:

    标签: java hibernate bean-validation hibernate-validator


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2018-04-22
      • 2019-11-20
      • 1970-01-01
      • 2020-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多