Jersey/JAX-RS:如何使用@Valid自动递归地层叠bean验证? [英] Jersey/JAX-RS : How to cascade beans-validation recursively with @Valid automatically?

查看:324
本文介绍了Jersey/JAX-RS:如何使用@Valid自动递归地层叠bean验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在泽西岛的REST资源端点中验证我的POJO:

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;

    ...
}

这似乎很好.

但是,仅当字段inner具有@Valid注释时,才会验证@Min(0)注释.在不是原始元素的每个字段中添加@Valid注释是不合适的.

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.

有没有一种方法可以告诉bean验证器自动递归地继续验证,即使没有@Valid批注也是如此?我希望我的POJO如下:

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;

    ...
}

推荐答案

实际上,根据规范,添加@Valid正是针对此用例.根据JSR 303规范:

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

除了支持实例验证外,还支持对象图的验证.图形验证的结果作为一组统一的约束违规返回. 考虑bean X包含类型为Y的字段的情况.通过使用@Valid注释对字段Y进行注释,验证器将在验证X时验证Y(及其属性).

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.

...

@Valid注释是递归应用的

The @Valid annotation is applied recursively

这篇关于Jersey/JAX-RS:如何使用@Valid自动递归地层叠bean验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆