@RequestMapping批注中路径和值属性之间的差异

问题描述 投票:25回答:3

以下两个属性和何时使用哪个属性有什么区别?

@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";
}
java spring rest spring-boot spring-restcontroller
3个回答
17
投票

如注释(和the documentation)中所述,valuepath的别名。 Spring经常将value元素声明为常用元素的别名。对于@RequestMapping(和@GetMapping,...),这是path属性:

这是path()的别名。例如,path()等效于@RequestMapping("/foo")

这样做的原因是@RequestMapping(path="/foo")元素是注释中的默认元素,因此它使您可以更简洁地编写代码。

其他示例是:

  • [value@RequestParamvalue
  • [name@PathVariablevalue
  • ...

但是,别名不仅限于注释元素,因为如您的示例所示,name@GetMapping的别名。]

只需查找@RequestMapping(method = RequestMethod.GET,您就会发现他们经常这样做。


7
投票

[references of AliasFor in their codeAliasFor的简写。

根据您的情况。@GetMapping@RequestMapping(method = RequestMethod.GET)的简写。

两者都是等效的。优先使用速记@GetMapping(path = "/usr/{userId}"),而不是更冗长的替代方法。您可以用@RequestMapping(value = "/usr/{userId}", method = RequestMethod.GET)做的一件事,而不是用@GetMapping做的一件事是提供多种请求方法。

@RequestMapping

需要提供多个Http动词时使用@GetMapping。>>

@RequestMapping(value = "/path", method = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT) public void handleRequet() { } 的另一种用法是当您需要为控制器提供顶层路径时。例如

@RequestMapping

4
投票

@RequestMapping是@RequestMapping的别名

© www.soinside.com 2019 - 2024. All rights reserved.