验证组继承

rdm*_*rdm 2 java hibernate hibernate-validator bean-validation

给定以下类和接口

class Person {

  @NotNull(groups=Both.class)
  private String name;
}
Run Code Online (Sandbox Code Playgroud)

验证组:

interface One {}
interface Two {}
interface Both extends One, Two {}
Run Code Online (Sandbox Code Playgroud)

打电话时

Person person = new Person();

validator.validate(person, One.class) 
Run Code Online (Sandbox Code Playgroud)

或者

validator.validate(person, Two.class)  
Run Code Online (Sandbox Code Playgroud)

我希望它应该是无效的,因为 name 为 null,但事实并非如此。事实证明,Both.class 组仅在 validator.validate(..., Both.class) 方法中使用时才有用。

JB *_*zet 6

你继承的方向是错误的。该Both组扩展One并且Two您可能将其视为“Both包含OneTwo”。这意味着,每次针对组进行验证时,组和Both的所有约束也都包含在, 中,从而得到验证。OneTwoBoth

但反之则不然:属于该群的约束Both既不是 的一部分One,也不是其中Two任何一个的一部分。因此,如果您验证 group 的约束One,则属于 Both 的约束将不会被验证。

请参阅http://beanvalidation.org/1.1/spec/#constraintdeclarationvalidationprocess-groupsequence-groupinheritance以获取参考。