I have a hard time believing I'm the only one who wants to do this, but I can't find any references to help me over my hurdle. Using Spring MVC and annotation-based validation (I'm using framework 4.0 and Java 1.7), consider a simple class hierarchy, as follows:

abstract class Foo {

    @Size(max=10, message = "The name has to be 10 characters or less.")
    private String name;

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

class Bar extends Foo {

}

class Bang extends Foo {

}

If I put a name in an instance of either Bar or Bang that's greater than 10 characters, I get the validation error I'm expecting. Let's suppose, though, that I still want Bar and Bang to be derived from the abstract base class Foo, but that I want the name attribute of the child classes to have different validations.

How do I annotate Bar and Bang so that Bar.name has a max length of, say, 12 characters while Bang.name has a max length of 8 characters?

Thanks much, Rob

有帮助吗?

解决方案

The short answer is that it is not possible in Bean Validation to disable constraints in super classes. There is a feature request here https://hibernate.atlassian.net/browse/BVAL-256 suggesting the introduction of annotations of the type @OverrideConstraint or @IgnoreInheritedConstraint. As of now, it is not possible to do this though.

See also http://lists.jboss.org/pipermail/beanvalidation-dev/2012-January/000128.html and https://hibernate.atlassian.net/browse/HV-548.

其他提示

Create a new field in the derived classes and override the methods.

class Bar extends Foo {
    @Size(max=12, message = "The name has to be 12 characters or less.")
    private String name;

    @Override
    public String getName() {
        return this.name;
    }

    @Override
    public void setName(String name) {
        this.name = name;
    }
}

you can put @Size(max=12, message = "The name has to be 12 characters or less.") annotation on getter method as well.

So just override the name field and put your personalized annotation on getter method. It will work same as putting the validation annotation on field. see example below:

class Bar extends Foo 
{
    @Override 
    @Size(max=12, message = "The name has to be 12 characters or less.")
    public void getName(String name)
        {
            this.name = name;
        }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top