java 你是否应该在同一个对象中使用 @NotNull 和 @JsonProperty(required)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45867473/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Should you use @NotNull and @JsonProperty(required) in the same object
提问by shammancer
So I'm looking at adding constraints to my json views.
所以我正在考虑向我的 json 视图添加约束。
I have class similar to this one
我有类似这门课
public class Person {
@JsonProperty(required = true)
@NotNull
@Size(max = 50)
private String name;
}
Should I keep both @JsonProperty(required = true)
and @NotNull
or should I remove one and why?
我应该保持双方@JsonProperty(required = true)
和@NotNull
或者我应该删除一个,为什么?
Just to be clear since Hymanson 2.6 @JsonProperty(required = true)
does throw an exception.
只是要清楚,因为 Hymanson 2.6@JsonProperty(required = true)
确实抛出了异常。
I'm using springfox-swagger and it looks like when I remove @JsonProperty(required = true)
the field in the swagger is marked as optional which it isn't.
我正在使用 springfox-swagger,看起来当我删除@JsonProperty(required = true)
swagger中的字段时,它被标记为可选,而事实并非如此。
I'm just wondering about the best practice in this situation.
我只是想知道在这种情况下的最佳实践。
采纳答案by cassiomolin
When using @JsonProperty
with required
set to true
on a field or method, Hymanson won't perform any validation. See the documentationfor further details.
在字段或方法上使用@JsonProperty
with required
set totrue
时,Hymanson 不会执行任何验证。有关更多详细信息,请参阅文档。
For validation purposes, consider @NotNull
from Bean Validation (a validation provider such as Hibernate Validatoris required to perform the validation).
出于验证目的,请考虑@NotNull
从 Bean 验证(需要使用Hibernate Validator等验证提供程序来执行验证)。
With Swagger, you also can use @ApiModelProperty
and set required
to true
to indicate that a field is mandatory.
使用 Swagger,您还可以使用@ApiModelProperty
和设置required
为true
来指示某个字段是必填字段。