嵌套验证组,Spring,JSR 303

LG_*_*LG_ 4 validation spring nested bean-validation validationgroup

我正在尝试在Spring应用程序中进行嵌套验证。

public class Parent{

   public interface MyGroup{}

   @NotNull(groups = MyGroup.class)
   private Child child;

   // getters and setters omited

}

public class Child{

   public interface OptionalGroup {}

   @NotBlank(groups = OptionalGroup.class)
   private String aField;

}
Run Code Online (Sandbox Code Playgroud)

我已经从javax.validation包中查看了@Valid,但它不支持组。我还检查了spring的@Validated注解,但无法将其应用于字段。

我想做这样的事情:

public class Parent{

   public interface MyGroup{}

   @NotNull(groups = MyGroup.class)
   @CascadeValidate(groups = MyGroup.class, cascadeGroups = OptionalGroup.class) 
   // 'groups' correspond to parent group and 'cascadeGroups' to a group that needs to be apply to the Child field.

   private Child child;

}
Run Code Online (Sandbox Code Playgroud)

然后,我可以在任何想要的地方进行务实的操作:

@Inject SmartValidator validator;

public void validationMethod(Parent parent, boolean condition) throws ValidationException {
   if(condition){
      MapBindingResult errors= new MapBindingResult(new HashMap<>(), target.getClass().getSimpleName());

      validator.validate(parent, errors, Parent.MyGroup.class); // validate all constraints associated to MyGroup

      if(errors.hasErrors()) throw new ValidationException(errors); // A custom exception
   }

}
Run Code Online (Sandbox Code Playgroud)

任何想法如何做到这一点?

非常感谢

LG_*_*LG_ 5

我终于找到了解决方案。其实我误会了@Valid它的目的。

关键是为Parent和child属性声明相同的组。

解决方案:

public class Parent{

   public interface MyGroup{}

   @NotNull(groups = MyGroup.class)
   @Valid // This annotation will launch nested validation
   private Child child;

   // getters and setters omited

}

public class Child{

   @NotBlank(groups = Parent.MyGroup.class) // Declare same group
   private String aField;

}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,当我这样做时:

 @Inject SmartValidator validator;

public void validationMethod(Parent parent, boolean condition) throws ValidationException {
   if(condition){
      MapBindingResult errors= new MapBindingResult(new HashMap<>(), target.getClass().getSimpleName());

      // validate all constraints associated to MyGroup (even in my nested objects)
      validator.validate(parent, errors, Parent.MyGroup.class); 

      if(errors.hasErrors()) throw new ValidationException(errors); // A custom exception
   }

}
Run Code Online (Sandbox Code Playgroud)

如果在我的子字段“ aField”中检测到验证错误,则第一个关联的验证错误代码(请参阅FieldError.codes)将为“ NotBlank.Parent.afield”。

我应该有更好的检查@Valid文档。