java - Jersey /JAX-RS : How to cascade beans-validation recursively with @Valid automatically?

标签 java jersey jax-rs bean-validation

我正在 Jersey 的 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 validator 自动递归地继续验证,即使没有 @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

关于java - Jersey /JAX-RS : How to cascade beans-validation recursively with @Valid automatically?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27980027/

相关文章:

java - 从 Java 类调用 Groovy Closure - 它会编译吗?

纬度和经度的Java String Split问题

javascript - 如何使用@JsInterop在GWT应用程序中公开增量DOM库的JS补丁功能

java - 为不同的运行时设置 Android 代码

java - Jackson 不忽略空值

java - entitymanager 的正确使用方法是什么

java - 服务器发送的事件丢失连接

java - 无法访问 Spring Boot 和 Jersey 应用程序中的某些 Controller

java - 使用 JUnit 测试休息服务

java - 服务器使用 JAX-RS 和 RESTeasy 在单个 URL 中向客户端发送 "ping request"