What is the difference between below two attributes and which one to use when?
@GetMapping(path = "/usr/{userId}")
public String findDBUserGetMapping(@PathVariable("userId") String userId) {
return "Test User";
}
@RequestMapping(value = "/usr/{userId}", method = RequestMethod.GET)
public String findDBUserReqMapping(@PathVariable("userId") String userId) {
return "Test User";
}
@GetMapping is an alias for @RequestMapping
value method is an alias for path method.
So both methods are similar in that sense.
@GetMapping
is a shorthand for@RequestMapping(method = RequestMethod.GET)
.In your case.
@GetMapping(path = "/usr/{userId}")
is a shorthand for@RequestMapping(value = "/usr/{userId}", method = RequestMethod.GET)
.Both are equivalent. Prefer using shorthand
@GetMapping
over the more verbose alternative. One thing that you can do with@RequestMapping
which you can't with@GetMapping
is to provide multiple request methods.Use
@RequestMapping
when you need to provide multiple Http verbs.Another usage of
@RequestMapping
is when you need to provide a top level path for a controller. For e.g.As mentioned in the comments (and the documentation),
value
is an alias topath
. Spring often declares thevalue
element as an alias to a commonly used element. In the case of@RequestMapping
(and@GetMapping
, ...) this is thepath
property:The reasoning behind this is that the
value
element is the default when it comes to annotations, so it allows you to write code in a more concise way.Other examples of this are:
@RequestParam
(value
→name
)@PathVariable
(value
→name
)However, aliases aren't limited to annotation elements only, because as you demonstrated in your example,
@GetMapping
is an alias for@RequestMapping(method = RequestMethod.GET
).Just looking for references of
AliasFor
in their code allows you to see that they do this quite often.