验证类层次结构覆盖

时间:2013-03-21 17:23:53

标签: java hibernate validation hibernate-validator

是否可以覆盖hibernate / javax验证的类层次结构? 或者如何通过扩展类来覆盖参数验证?

使用@Valid注释并在我的类中设置javax验证注释。我想要一个扩展类,其中删除验证。 我发现hibernate验证在整个类层次结构中循环,并检查甚至在超类中的验证。 我在使用Spring MVC设置的基于Json的REST API中使用它。

示例:

public class Parent {
    protected Integer numChildren;

    @NotNull(message = "NumChildren has to be set.") 
    @Size(min 1, max 10, message = "A partent has to have at least one kid.")
    public Integer getNumChildren() {
        return numChildren;
    }

    public void setNumChildren(Integer numChilds) {
        this.numChildren = numChilds;
    }
}

public class Child extends Parent {

    // A child doesnt have to have kids, but can, so I want to override this parameter
    // and remove the validation requirement, and make it just optional.
    @Override
    public Integer getNumChildren() {
        return super.numChildren;
    }
}

最诚挚的问候, 马库斯

1 个答案:

答案 0 :(得分:0)

Bean Validation不允许在超类中禁用/更改约束。约束总是结合在一起。我想要走的路可以通过群组,例如 ParentChecks 组和 ChildChecks 组。将特定于子父级的约束分配给相应的组。然后,您可以将父项的默认组重新定义为 ParentChecks ,_ Parent_,将子项重新定义为 ChildChecks Child 。这应该有用。

相关问题