我一直在寻找一种方法来验证 bean 的某些属性而不是所有属性。

例如:

public Class TestA {

 @NotEmpty
 private String first;

 @NotEmpty
 @Size(min=3,max=80)
 private String second;

 //getters and setters

}

我有另一个名为“TestB”的类,它引用类“TestA”,如下所示

public Class TestB {

 @NotEmpty
 private String other;

 @Valid
 private TestA testA; 

 //public getters and setters
}

是否可以编写自定义注释验证器来仅验证某些属性?像下面的东西...

public Class TestB {

 @NotEmpty
 private String other;

 @CustomValid(properties={"second"})
 private TestA testA; 

 //public getters and setters
}
有帮助吗?

解决方案

使用 groups 属性来做到这一点。它看起来像这样:

public Class TestA {

 @NotEmpty(groups = {Second.class})
 private String first;

 @NotEmpty(groups = {Second.class})
 @Size(min=3,max=80, groups = {Second.class})
 private String second;

 //getters and setters

}

public Class TestB {

 @NotEmpty
 private String other;

 @Valid
 private TestA testA; 

 //public getters and setters
}

在哪里 Second 是一个在某处定义的空接口。

有关更多详细信息,请参阅文档中的示例: 2.3.验证组 另外,如果您使用 Spring >= 3.1 您可能会对 @Validates 允许启用指定组验证的注释。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top