Spring MVC Validation for Inherited Classes

It’s hard for me to believe that I am the only one who wants to do this, but I can’t find any links to help me overcome the obstacle. Using Spring MVC and annotation-based validation (I am 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 the name in an instance of any Bar or Bang string containing more than 10 characters, I get the validation error that I expect. Suppose, however, that I still want Bar and Bang to be derived from the abstract base class Foo, but I want the name attribute of the child classes to have different checks.

Bar Bang, Bar.name , , 12 , Bang.name 8

, Rob

+4
3

@Size(max=12, message = "The name has to be 12 characters or less.") getter.

getter. , . . :

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;
        }
}
+2

.

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;
    }
}
+1

Source: https://habr.com/ru/post/1527404/


All Articles