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

58

以下两个属性有什么区别,应该在什么情况下使用哪一个?

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

1
根据文档,它们是相同的: “这是path()的别名。例如,@RequestMapping(“/foo”)等同于@RequestMapping(path =“/foo”)。 - Guillaume Ruchot
3个回答

44
文档所述,valuepath的别名。Spring通常将value元素声明为常用元素的别名。在@RequestMapping(和@GetMapping, ...)中,这是path属性。

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

其背后的原因是value元素是注释中的默认值,因此可以更简洁地编写代码。
其他示例包括:
  • @RequestParamvaluename
  • @PathVariablevaluename
  • ...
然而,别名不仅限于注释元素,正如您在示例中演示的那样,@GetMapping@RequestMapping(method = RequestMethod.GET)的别名。

仅查找他们代码中AliasFor的引用,就可以看到他们经常这样做。


20

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

2
@Juzer Ali @GetMapping(path = "/usr/{userId}"), @GetMapping(value = "/usr/{userId}")@GetMapping("/usr/{userId}") 都是相同的吗? - Antony Vimal Raj

8

@GetMapping是@ RequestMapping的别名。

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

value方法是path方法的别名。

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

因此,两种方法在这个意义上是相似的。


第一个是"@GetMapping",不是"@RequestMapping"。 - Guillaume Ruchot

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接