Jersey/JAX-RS:如何自动使用@Valid 递归级联bean-validation?
Jersey/JAX-RS : How to cascade beans-validation recursively with @Valid automatically?
我正在泽西岛的 REST 资源端点验证我的 POJO:
public class Resource {
@POST
public Response post(@NotNull @Valid final POJO pojo) {
...
}
}
public class POJO {
@NotNull
protected final String name;
@NotNull
@Valid
protected final POJOInner inner;
...
}
public class POJOInner {
@Min(0)
protected final int limit;
...
}
这似乎工作正常。
但是,@Min(0)
注释仅在字段 inner
具有 @Valid
注释时才被验证。将 @Valid
注释添加到每个不是原始字段的字段感觉不对。
有没有办法告诉 bean 验证器自动递归地继续验证,即使没有 @Valid
注释存在?我希望我的 POJO
如下所示:
public class POJO {
@NotNull
protected final String name;
@NotNull
protected final POJOInner inner;
...
}
实际上,根据规范,添加@Valid 正是针对此用例。来自 JSR 303 规范:
In addition to supporting instance validation, validation of graphs of object is also supported. The result of a graph validation is returned as a unified set of constraint violations.
Consider the situation where bean X contains a field of type Y. By annotating field Y with the @Valid annotation, the Validator will validate Y (and its properties) when X is validated.
...
The @Valid annotation is applied recursively
我正在泽西岛的 REST 资源端点验证我的 POJO:
public class Resource {
@POST
public Response post(@NotNull @Valid final POJO pojo) {
...
}
}
public class POJO {
@NotNull
protected final String name;
@NotNull
@Valid
protected final POJOInner inner;
...
}
public class POJOInner {
@Min(0)
protected final int limit;
...
}
这似乎工作正常。
但是,@Min(0)
注释仅在字段 inner
具有 @Valid
注释时才被验证。将 @Valid
注释添加到每个不是原始字段的字段感觉不对。
有没有办法告诉 bean 验证器自动递归地继续验证,即使没有 @Valid
注释存在?我希望我的 POJO
如下所示:
public class POJO {
@NotNull
protected final String name;
@NotNull
protected final POJOInner inner;
...
}
实际上,根据规范,添加@Valid 正是针对此用例。来自 JSR 303 规范:
In addition to supporting instance validation, validation of graphs of object is also supported. The result of a graph validation is returned as a unified set of constraint violations. Consider the situation where bean X contains a field of type Y. By annotating field Y with the @Valid annotation, the Validator will validate Y (and its properties) when X is validated.
...
The @Valid annotation is applied recursively