我可以覆盖 jsr-303 验证注释吗 [英] can I override a jsr-303 validation annotation
问题描述
我有一个如下的测试:
公共类TestSizeAnnotation{public static void main(String[] args){System.out.println(Validation.buildDefaultValidatorFactory().getValidator().validate(new C()));}公共静态类 P{私人列表<字符串>lst = newArrayList("AA");@Size(max=0, message="P")公共列表<字符串>获取Lst(){返回列表;}public void setLst(List lst){this.lst = lst;}}公共静态类 C 扩展 P{@覆盖@Size(max=5, message="C")公共列表<字符串>获取Lst(){返回 super.getLst();}}}
具有以下输出:[ConstraintViolationImpl{interpolatedMessage='P', propertyPath=lst, rootBeanClass=class com....validator.TestSizeAnnotation$C, messageTemplate='P'}]
但是,我希望注释可以被 @Size
覆盖,并且不会出现警告.
有没有办法做到这一点?
我发现一个 bug 似乎与此有关,但我运行的是 4.2.0 final 仍然得到上述行为.
JSR-303 实际上不支持覆盖验证注释.相反,子类中重写方法的注释将累积应用:来自规范的第 3.3 节:
<前>约束声明可以放在接口上.对于给定的类,超类和接口上的约束声明是由 Bean 验证提供程序评估.规则在第 3.4.5 节.约束声明的效果是累积的.约束声明将与定义的任何约束一起验证超类 getter根据 Java 语言在 getter 的覆盖版本上规范可见性规则.I have a test like below:
public class TestSizeAnnotation
{
public static void main(String[] args)
{
System.out.println(Validation.buildDefaultValidatorFactory().getValidator().validate(new C()));
}
public static class P
{
private List<String> lst = newArrayList("AA");
@Size(max=0, message="P")
public List<String> getLst()
{
return lst;
}
public void setLst(List<String> lst)
{
this.lst = lst;
}
}
public static class C extends P
{
@Override
@Size(max=5, message="C")
public List<String> getLst()
{
return super.getLst();
}
}
}
with the following output:
[ConstraintViolationImpl{interpolatedMessage='P', propertyPath=lst, rootBeanClass=class com....validator.TestSizeAnnotation$C, messageTemplate='P'}]
However, I expected that the annotation can @Size
be overridden, and no warning will appear.
Is there a way to accomplish that?
EDIT: I found a bug seems related to that, but I run 4.2.0 final and still get the above behavior.
Overriding validation annotations is actually not supported for JSR-303. Instead annotations on overridden methods in the subclass will be applied cumulatively: From section 3.3 of the specification:
A constraint declaration can be placed on an interface. For a given class, constraint declarations held on super- classes as well as interfaces are evaluated by the Bean Validation provider. Rules are formally described in Section 3.4.5. The effect of constraint declarations is cumulative. Constraints declared on a superclass getter will be validated along with any constraints defined on an overridden version of the getter according to the Java Language Specification visibility rules.
这篇关于我可以覆盖 jsr-303 验证注释吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!