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

Deadly 提交于 2019-12-04 15:03:30

问题


I am validating my POJOs in a REST resource endpoint in Jersey:

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;

    ...
}

This seems to work fine.

However, the @Min(0) annotation is only verified if the field inner has the @Valid annotation. It doesn't feel right to add the @Valid annotation to each field which isn't a primitive.

Is there a way to tell the bean validator to automatically recursively continue the validation, even when no @Valid annotation is present? I would like my POJO to be as following:

public class POJO {
    @NotNull
    protected final String name;

    @NotNull
    protected final POJOInner inner;

    ...
}

回答1:


Actually, according to the specification, adding @Valid is exactly for this usecase. From the JSR 303 specification:

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



来源:https://stackoverflow.com/questions/27980027/jersey-jax-rs-how-to-cascade-beans-validation-recursively-with-valid-automati

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!