[英]custom bean validation in java
我一直在寻找一种方法来仅针对某些属性而不是所有属性来验证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
批注中可能会很有趣, @Validates
批注允许启用指定组的验证。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.