代码之家  ›  专栏  ›  技术社区  ›  Raj

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

  •  49
  • Raj  · 技术社区  · 7 年前

    以下两个属性之间的区别是什么,何时使用哪一个?

    @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";
    }
    
    3 回复  |  直到 5 年前
        1
  •  35
  •   Dimitri Mestdagh    7 年前

    如评论中所述(和 the documentation ), value 是的别名 path 春天经常宣告 价值 元素作为常用元素的别名。在以下情况下 @RequestMapping (和 @GetMapping ,…)这是 路径 属性:

    这是的别名 path() 例如 @RequestMapping("/foo") 相当于 @RequestMapping(path="/foo") .

    这背后的原因是 价值 元素是注释的默认值,因此它允许您以更简洁的方式编写代码。

    其他例子包括:

    • @RequestParam ( 价值 ††† name )
    • @PathVariable ( 价值 ††† 名称 )
    • 。。。

    但是,别名不仅限于注释元素,因为正如您在示例中所演示的, @获取映射 是的别名 @RequestMapping(method = RequestMethod.GET ).

    只是在寻找 references of AliasFor in their code 让您看到他们经常这样做。

        2
  •  17
  •   Juzer Ali    7 年前

    @GetMapping @RequestMapping(method = RequestMethod.GET) .

    在你的情况下。 @GetMapping(path = "/usr/{userId}") @RequestMapping(value = "/usr/{userId}", method = RequestMethod.GET) .

    两者都是等效的。喜欢使用速记 @获取映射 在更冗长的备选方案上。你可以做一件事 @RequestMapping 你不能用它 @获取映射 是提供多种请求方法。

    @RequestMapping(value = "/path", method = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT)
    public void handleRequet() {
    
    }
    

    使用 @请求映射 当您需要提供多个Http谓词时。

    的其他用法 @请求映射 需要为控制器提供顶级路径时。例如:。

    @RestController
    @RequestMapping("/users")
    public class UserController {
    
        @PostMapping
        public void createUser(Request request) {
            // POST /users
            // create a user
        }
    
        @GetMapping
        public Users getUsers(Request request) {
            // GET /users
            // get users
        }
    
        @GetMapping("/{id}")
        public Users getUserById(@PathVariable long id) {
            // GET /users/1
            // get user by id
        }
    }
    
        3
  •  6
  •   Ori Marko    7 年前

    @GetMapping 是@RequestMapping的别名

    @GetMapping是一个组合注释,用作@RequestMapping(method=RequestMethod.GET)的快捷方式。

    value 方法是路径方法的别名。

    这是path()的别名。例如,@RequestMapping(“/foo”)等同于@RequestMapping(path=“/foo”)。

    所以这两种方法在这个意义上是相似的。