@RequestMapping批注中的路径和值属性之间的区别 [英] Difference between path and value attributes in @RequestMapping annotation

查看:62
本文介绍了@RequestMapping批注中的路径和值属性之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

这是等效于 @RequestMapping(path ="/foo").

其背后的原因是 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆