代码之家  ›  专栏  ›  技术社区  ›  nesohc

验证类层次结构覆盖

  •  1
  • nesohc  · 技术社区  · 12 年前

    是否可以覆盖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 回复  |  直到 12 年前
        1
  •  0
  •   Hardy    12 年前

    Bean验证不允许禁用/更改超级类中的约束。约束总是组合在一起的。我想应该是通过小组的方式,例如 家长检查 组和a 儿童支票 组将特定于子对象的父对象的约束指定给相应的组。然后,您可以重新定义要成为的父对象的默认组 家长检查 ,_Parent_和给孩子的那个 儿童支票 , 小孩 。这应该行得通。