我可以覆盖jsr-303验证注释

时间:2012-01-30 16:44:35

标签: java hibernate annotations bean-validation

我有如下测试:

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();
    }

}
}

输出如下:
[ConstraintViolationImpl{interpolatedMessage='P', propertyPath=lst, rootBeanClass=class com....validator.TestSizeAnnotation$C, messageTemplate='P'}]

但是,我希望注释可以被覆盖@Size,并且不会出现警告 有办法实现吗?

编辑:我发现bug似乎与此有关,但我在4.2.0决赛中仍然遇到上述行为。

3 个答案:

答案 0 :(得分:15)

JSR-303实际上不支持覆盖验证注释。而是应用累积来应用子类中重写方法的注释:来自规范的第3.3节:

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.

答案 1 :(得分:3)

您可以通过xml配置来修改注释配置的验证:

http://docs.jboss.org/hibernate/validator/4.2/reference/en-US/html_single/#validator-xmlconfiguration

在您的情况下,如果您在validation.xml文件中为getList()methid声明了不同的验证(或没有验证),它将覆盖@Size注释。

答案 2 :(得分:1)

只是为了记录,我找到了绕过我的问题:

public class TestSizeAnnotation
{
    public static void main(String[] args)
    {
        System.out.println("c " + 
                Validation.buildDefaultValidatorFactory().getValidator().validate(new C(), Default.class, SizeGroup2.class));
        System.out.println("p " + 
                Validation.buildDefaultValidatorFactory().getValidator().validate(new P(), Default.class, SizeGroup.class));
    }
    public static interface SizeGroup {}
    public static interface SizeGroup2 {}
    public static class P 
    {
        private List<String> lst = newArrayList("AA");
        @Size(max=0, message="P" , groups=SizeGroup.class)
        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", groups=SizeGroup2.class)
        public List<String> getLst()
        {
            return super.getLst();
        }

    }
}