Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC Validation of Inherited Classes

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

like image 990
RobAllen Avatar asked Feb 17 '14 23:02

RobAllen


1 Answers

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.

like image 155
Hardy Avatar answered Sep 30 '22 17:09

Hardy