以下两个属性和何时使用哪个属性有什么区别?
@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";
}
如注释(和the documentation)中所述,value
是path
的别名。 Spring经常将value
元素声明为常用元素的别名。对于@RequestMapping
(和@GetMapping
,...),这是path
属性:
这是
path()
的别名。例如,path()
等效于@RequestMapping("/foo")
。
这样做的原因是@RequestMapping(path="/foo")
元素是注释中的默认元素,因此它使您可以更简洁地编写代码。
其他示例是:
value
(@RequestParam
→value
)name
(@PathVariable
→value
)但是,别名不仅限于注释元素,因为如您的示例所示,name
是@GetMapping
的别名。]
只需查找@RequestMapping(method = RequestMethod.GET
,您就会发现他们经常这样做。
[references of AliasFor
in their code是AliasFor
的简写。
根据您的情况。@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
@RequestMapping
是@RequestMapping的别名