Difference between path and value attributes in @RequestMapping annotation

Raj picture Raj · May 15, 2018 · Viewed 21.1k times · Source

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";
}

Answer

g00glen00b picture g00glen00b · May 15, 2018

As mentioned in the comments (and the documentation), value is an alias to path. Spring often declares the value element as an alias to a commonly used element. In the case of @RequestMapping (and @GetMapping, ...) this is the path property:

This is an alias for path(). For example @RequestMapping("/foo") is equivalent to @RequestMapping(path="/foo").

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 (valuename)
  • @PathVariable (valuename)
  • ...

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.