Reputation: 21482
There appear to be two documented ways of marking a parameter of a Spring controller method as optional:
(1) Add required=false
to the @RequiredParam
annotation:
public String books(@RequestParam(name = "category", required = false) String category) {
(2) Change the parameter type to Optional<T>
:
public String books(@RequestParam(name = "category") Optional<String> category) {
But it appears the following also works:
(3) Place the @Nullable
annotation on the parameter:
public String books(@Nullable @RequestParam(name = "category") String category) {
I prefer #3, but I would feel better about using it if it were documented. I have searched for documentation, but all I can find is what is documented for @Nullable:
A common Spring annotation to declare that annotated elements can be null under some circumstance.
I cannot find a single example showing @Nullable
used with @RequestParam
.
Does anyone know if and where this is documented?
Upvotes: 3
Views: 7508
Reputation: 4057
@Nullable
is a well-known annotation which can be applied to fields, methods, and parameters. Knowing its popularity maybe Spring doesn't mind not mentioning it. So, feel fry to use it.
Now coming to the choice of using validation: I will either go with @Nullable
or required = false
.
Optional<T>
came in java 8 for preventing NullPointerException
. So, <Optional<String>
would never give you the null
value, it would either return the value
or the Optional.empty
. And to get the value from this you would need to call an extra method get()
.
So, if the whole idea is to mark any query paramter as nullable
, use either @Nullable
or required=false
Upvotes: 3