gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 20:23:19 29 4
gpt4 key购买 nike

我正在 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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com