Spring,JSR 303 - 嵌套字段上的验证组

时间:2018-03-17 03:05:19

标签: spring validation bean-validation

以下是示例,优于单词:

public class Person{

   private String name;

   // 1 ) @Valid(FirstAdress.class) -> The attribute value is undefined for the annotation type Valid
   // 2 ) @Validated(FirstAdress.class) -> The annotation @Validated is disallowed for this location
   @Valid
   private Adress firstAdress;

   // 1 ) @Valid(SecondAdress.class)
   // 2 ) @Validated(SecondAdress.class)
   @Valid
   private Adress secondAdress;

}

public class Adress {

   @Size(min = 5, groups = { FirstAdress.class })
   @Size(min = 10, groups = { SecondAdress.class })
   private String city;

   public interface FirstAdress{
   }

   public interface SecondAdress{
   }
}

因此,对于firstAdress对象,字段city必须至少为5个字符,而对于secondAdress,该city必须至少为10个字符(仅作为示例)。

代码中的解决方案1)和2)还没有工作/可用,我想知道我想做什么是可能的,或者是否有其他方法可以做到。

非常感谢!

1 个答案:

答案 0 :(得分:0)

我试过了:

@Valid
@ConvertGroup(to = FirstAdress.class)
private Adress firstAdress;

@Valid
@ConvertGroup(to = SecondAdress.class)
private Adress secondAdress;

现在看起来很有效!如果这个解决方案出现问题,我会更新这篇文章:)