【问题标题】:Access parent property path in custom validator在自定义验证器中访问父属性路径
【发布时间】:2019-09-06 09:22:09
【问题描述】:

我正在编写自定义javax.validation.ConstraintValidator。我想在我的ConstraintViolation 上包含一个自定义属性路径,包括父属性路径。所以:

class BaseClass {
  @Valid MyProperty first;
}

@MyValidator class MyProperty {
  String someField;
}

class MyValidatorImpl implements ConstraintValidator<MyValidator, MyProperty> { 
  // ...
  public boolean isValid(MyProperty value, ConstraintValidatorContext context) {
     context.disableDefaultConstraintViolation();
     context.buildConstraintViolationWithTemplate("My message")
         // How to access the parent property name "first" here? 
         .addPropertyNode("my custom property") 
         .addConstraintViolation()
  }
}

任何帮助将不胜感激。

【问题讨论】:

    标签: java jakarta-ee bean-validation


    【解决方案1】:

    显然,答案是在.addPropertyNode() 调用之后添加.addBeanNode() 调用。这实际上会在属性名称之前添加父节点名称​​。请注意,您不能在调用addPropertyNode() 之前调用addBeanNode(),因为它背后的构建器不允许这样做。

    【讨论】:

      猜你喜欢
      • 2021-04-09
      • 2013-01-29
      • 2018-12-19
      • 1970-01-01
      • 2015-11-09
      • 1970-01-01
      • 1970-01-01
      • 2015-04-26
      • 1970-01-01
      相关资源
      最近更新 更多