Spring MVC Validation of Inherited Classes

孤街醉人 提交于 2019-12-01 04:09:04

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;
        }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!