@RequestMapping批注中的路径和值属性之间的区别 [英] Difference between path and value attributes in @RequestMapping annotation
问题描述
以下两个属性和何时使用哪个属性有什么区别?
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";
}
推荐答案
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:
其背后的原因是 value
元素是注释的默认元素,因此它使您可以更简洁地编写代码.
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.
其他示例包括:
-
@RequestParam
(值
→名称
) -
@PathVariable
(值
→名称
) - ...
但是,别名并不仅限于注释元素,因为如您的示例所示, @GetMapping
是 @RequestMapping(方法= RequestMethod.GET
).
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
).
只需查找在其代码中对 AliasFor
的引用使您看到他们经常这样做.
Just looking for references of AliasFor
in their code allows you to see that they do this quite often.
这篇关于@RequestMapping批注中的路径和值属性之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!