@RequestMapping注解中path属性和value属性的区别

新手上路,请多包涵

以下两个属性之间有什么区别,什么时候使用哪个?

 @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";
}

原文由 Raj 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 3.2k
2 个回答

如评论(和 文档)中所述valuepath 的别名。 Spring 通常将 value 元素声明为常用元素的别名。在 @RequestMapping 的情况下(和 @GetMapping ,…)这是 path 属性:

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

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

这方面的其他例子是:

  • @RequestParamvaluename
  • @PathVariablevaluename

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

只要 在他们的代码中查找 AliasFor 的引用, 您就会发现他们经常这样做。

原文由 g00glen00b 发布,翻译遵循 CC BY-SA 4.0 许可协议

@GetMapping@RequestMapping(method = RequestMethod.GET) 的简写。

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

两者是等价的。更喜欢使用速记 @GetMapping 而不是更冗长的替代方法。您可以使用 @RequestMapping 而不能使用 @GetMapping 做的一件事是提供多种请求方法。

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

}

当您需要提供多个 Http 动词时,请使用 @RequestMapping

@RequestMapping 的另一个用法是当您需要为控制器提供顶级路径时。例如

@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
    }
}

原文由 Juzer Ali 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题