Purpose of @NotNull.List

情到浓时终转凉″ 提交于 2019-12-12 08:47:33

问题


When I looked among the standard constraints in Bean Validation API (JSR-303), I found the NotNull.List annotation. Its description is:

Defines several @NotNull annotations on the same element

This is valid syntax:

@NotNull.List({@NotNull, @NotNull})
private Object myObject;

But it makes no sense. Either the object is null or it is not. When would you use this annotation?

There are several other similar annotations like AssertFalse.List and AssertTrue.List.


回答1:


You can have multiple @NotNull annotations that are mutually exclusive based on the group attribute.

@NotNull.List({@NotNull(groups=Foo.class,message="Some message!"), 
               @NotNull(groups=bar.class, message="Some other message!"})
private Object myObject;

I do agree it's a little silly for this example since only the payload and message can be affected, but it's probably there to remain consistent with the other annotations.

See here for more details.




回答2:


As to the @NotNull case, multiple @NotNull annotations might be needed for different validation groups as @dfb explained. But the same may be accomplished by listing those groups in the groups attribute. This is well explained here with test cases

In the bean validation API javadoc, for every constraint annotation, there's a corresponding .List annotation. For example, for @NotNull, there's @NotNull.List, for which JavaDoc says:

Defines several @NotNull annotations on the same element

What would you accomplish with multiple @NotNull annotations that you cannot accomplish with one @NotNull?



来源:https://stackoverflow.com/questions/28610788/purpose-of-notnull-list

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