@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) {
}
@GetMapping
public Users getUsers(Request request) {
}
@GetMapping("/{id}")
public Users getUserById(@PathVariable long id) {
}
}