我有一个如下所示的 POJO 类,
@XmlRootElement
public class JsonReply {
@XmlElement(nillable = false)
String callResult;
@XmlElement(nillable=false)
String returnobj;
@NotNull
String callError;
public String getCallResult() {
return callResult;
}
public void setCallResult(String callResult) {
this.callResult = callResult;
}
public String getCallError() {
return callError;
}
public void setCallError(String callError) {
this.callError = callError;
}
为了避免空字符串,我使用了许多注释,例如 Lombok 的 @NotNull 和 javax.xml.bind.annotation.XmlRootElement 的 @XmlElement(nillable=false)。我的问题是是否有任何其他方式或注释来限制整数或字符串的长度,例如 min=5 和 max=10。
@Size(max=10)
@Max(5)
Integer sampleint;
我正在使用 jackson 。如果 Jackson 本身有任何注释(例如 @JsonIgnoreProperties),那就很好了。
谢谢!
最佳答案
Bean 验证
您可以考虑 Bean Validation 。它基于注释并与各种框架集成。引用实现是 Hibernate Validator 。
以下是一些可能对您有用的亮点:
对于
String
验证,您可能感兴趣的现成注释是@Size
。对于数字验证,请考虑
@Min
、@Max
、@DecimalMin
、@DecimalMax
和@Digits
。使用
@NotNull
不接受null
值。
有关更多详细信息,请检查 javax.validation.constraints
包。
Bean 验证和 Jersey 2.x
Jersey 2.x 中的 Bean 验证支持作为扩展模块提供,需要在您的 pom.xml
文件中明确提及(如果使用 Maven):
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-bean-validation</artifactId>
<version>2.23.2</version>
</dependency>
如果您不使用 Maven,请确保类路径上也具有所有传递依赖项(请参阅 jersey-bean-validation
工件)。该模块直接依赖于 Hibernate Validator,它提供了 Bean Validation 规范最常用的实现。
在 Jersey 中,Bean Validation 模块是 auto-discoverable features ,也就是说,它是您不需要在服务器上显式注册其功能 ( ValidationFeature
) 的模块之一当您将 jersey-bean-validation
模块添加到类路径时,会自动发现并注册。
有关更多详细信息,请检查 Jersey documentation about Bean Validation support 。
关于java - java POJO中使用注释限制输入长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38910461/