Spring MVC验证继承的类 [英] Spring MVC Validation of Inherited Classes

查看:159
本文介绍了Spring MVC验证继承的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难相信我是唯一想要这样做的人,但是我找不到任何帮助我克服障碍的参考.使用Spring MVC和基于注释的验证(我使用的是框架4.0和Java 1.7),请考虑一个简单的类层次结构,如下所示:

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 {

}

如果我在大于10个字符的Bar或Bang实例中放置 name ,则会收到我期望的验证错误.但是,让我们假设,我仍然希望Bar和Bang是从抽象基类Foo派生的,但是我希望子类的name属性具有不同的验证.

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.

如何注释Bar和Bang,以使 Bar.name 的最大长度为12个字符,而 Bang.name 的最大长度为8个字符?

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?

非常感谢, 罗布

推荐答案

简短的答案是,在Bean验证中无法禁用超类中的约束. https://hibernate.atlassian.net/browse/BVAL-256 a>建议引入@OverrideConstraint或@IgnoreInheritedConstraint类型的注释.截至目前,这是不可能的.

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.

另请参见 http://lists.jboss.org/pipermail/beanvalidation-dev/2012-January/000128.html https://hibernate .atlassian.net/browse/HV-548 .

这篇关于Spring MVC验证继承的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆