@RequestMapping 是 Spring MVC 框架中最核心的注解之一,用于将 HTTP 请求映射到控制器(Controller)中的处理方法,实现请求路由功能。
基本作用
建立 URL 路径 与 控制器方法 之间的映射关系。
可标注在 类级别(定义公共路径前缀)或 方法级别(定义具体请求路径)。
常用属性
属性 类型 说明
value / path String[] 指定请求路径,支持多个路径(如 "/user", "/api/user")
method RequestMethod[] 指定支持的 HTTP 方法(如 GET, POST)
params String[] 限定请求必须包含特定参数(如 "username=admin")
headers String[] 限定请求必须包含特定请求头(如 "Content-Type=application/json")
consumes String[] 限定请求的内容类型(如 application/json)
produces String[] 限定响应的内容类型(如 application/xml)
示例:
@RequestMapping(value = "/user", method = RequestMethod.GET)
等价于 @GetMapping("/user")
派生注解(推荐使用)
为提升代码可读性,Spring 提供了针对常用 HTTP 方法的简化注解:
@GetMapping → @RequestMapping(method = GET)
@PostMapping → @RequestMapping(method = POST)
@PutMapping → @RequestMapping(method = PUT)
@DeleteMapping → @RequestMapping(method = DELETE)
@PatchMapping → @RequestMapping(method = PATCH)
推荐场景:当接口仅支持一种 HTTP 方法时,优先使用派生注解,语义更清晰、代码更简洁。
组合使用示例
@RestController
@RequestMapping("/api/users") // 类级别:公共前缀
public class UserController {
@GetMapping("/{id}") // 方法级别:/api/users/123
public User getUser(@PathVariable Long id) {
return userService.findById(id);
}
@PostMapping // /api/users
public User createUser(@RequestBody User user) {
return userService.save(user);
}
@RequestMapping(value = "/multi", method = {RequestMethod.GET, RequestMethod.POST})
public String multiMethod() {
return "支持 GET 和 POST";
}
}
路径变量与通配符
路径变量:使用 {} 定义变量,配合 @PathVariable 获取值
@GetMapping("/user/{id}")
public String getUser(@PathVariable("id") Long userId) { ... }
Ant 风格通配符:
*:匹配任意单个路径段(如 /user/* 匹配 /user/123)
‌**:匹配任意多层路径(如 /user/**‌ 匹配 /user/123/profile)
注意事项
- 默认支持所有 HTTP 方法:若未指定 method,则该方法响应所有请求方式(GET、POST、PUT 等)。
- 避免映射冲突:同一路径+方法组合不能重复映射到多个方法,否则启动报错 Ambiguous mapping。
- 类路径 + 方法路径 = 最终访问路径:如类上 /api,方法上 /user,则完整路径为 /api/user。