1

如何为此类配置不同的验证策略:

   @MappedSuperClass
    public class Base{
       @Size(min=4)
       String name;
   }

所以:

public class Child extends Base{
   @NotBlank
   String surname;
}

如果我创建基类,我想关闭验证。但是,如果我创建子类,我想打开验证。

我怎么能这样?

更新

我使用 spring 类验证BindingResult

4

1 回答 1

1

您可以定义两个验证组,例如 BaseGroup 和 ChildGroup。然后,您始终可以仅使用 ChildGroup 验证您的对象,因此在基类的情况下,所有检查都将被省略。

更新。例子:

 @MappedSuperClass
 public class Base{
    @Size(min=4, groups = BaseGroup.class)
    String name;
}

public class Child extends Base{
    @NotBlank(groups = ChildChecks.class)
    String surname;
} 

Base base = new Base();
Set<ConstraintViolation<Base>> baseViolations = validator.validate( base , ChildChecks.class);
// I suppose that this list will always be empty, because no constraints are defined for ChildChecks group in Base class

Child child = new Child();
Set<ConstraintViolation<Child>> childViolations = validator.validate( child,  BaseGroup.class, ChildChecks.class );
// All checks wil be verified here, because we use two groups
于 2013-09-19T13:25:30.153 回答