企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持知识库和私有化部署方案 广告
下面对 `@RequestMapping` 做一次系统性梳理,并给出一张“场景-代码-注意点”三列表,方便你把 **所有 HTTP 方法、所有常用属性** 一次掌握。 >[info]一、它到底是什么 1. 元注解:`@RequestMapping` 是 Spring MVC 的“根注解”,所有派生快捷注解(`@GetMapping/@PostMapping/…`)的基础。 2. 目的:把 **任意 HTTP 请求(GET/POST/PUT/DELETE/…)** 映射到控制器类或方法,并统一配置路径、方法、头信息、内容协商等。 >[info]二、它能做什么 - 同时支持类级别 + 方法级别的“二级路由”。 - 一次性声明多种 HTTP 方法、多个路径、多个头信息。 - 与 Spring Security、Swagger、跨域、异步、响应式无缝整合。 >[info]三、常用场景与示例 下表覆盖 99% 的日常需求,可直接复制粘贴使用。 | # | 场景 | 经典代码 | 注意点/最佳实践 | |---|------|----------|-----------------| | 1 | 类级别统一前缀 | `@RequestMapping("/api/v1") public class UserController {}` | 方法上再写相对路径即可 | | 2 | 指定 GET | `@RequestMapping(value="/users", method=RequestMethod.GET)` | 与 `@GetMapping("/users")` 等价 | | 3 | 多方法合一 | `@RequestMapping(value="/users", method={GET,POST})` | 一个方法同时处理 GET+POST,常用于老接口 | | 4 | 多路径 | `@RequestMapping(path={"/users","/people"})` | 或 `value={...}`,二者互为别名 | | 5 | 路径变量 | `@RequestMapping("/user/{id}")` + `@PathVariable Long id` | 与 `@GetMapping` 完全一致 | | 6 | 正则路径 | `@RequestMapping("/user/{id:\\d+}")` | 仅匹配数字 | | 7 | 查询参数 | `@RequestMapping("/search")` + `@RequestParam String q` | 同样支持 `defaultValue`、`required=false` | | 8 | Header 条件 | `@RequestMapping(headers="X-API-VERSION=1")` | 必须带指定头才能命中 | | 9 | Accept 头 | `@RequestMapping(produces="application/json")` | 决定返回格式 | |10 | Content-Type | `@RequestMapping(consumes="application/json")` | 决定接收格式 | |11 | 组合条件 | `@RequestMapping(path="/users", method=GET, headers="X-Token", produces="application/json")` | 条件同时满足才命中 | |12 | 通配符 | `@RequestMapping("/static/**")` | 常用于静态资源 | |13 | 默认映射 | `@RequestMapping` | 缺省所有属性 ⇒ 捕获任意方法、任意路径,慎用 | |14 | 视图跳转 | `@Controller` 类中 `@RequestMapping("/home") public String home(){return "home";}` | 返回视图名 | |15 | REST 风格 | `@RestController` 类中 `@RequestMapping(value="/books", method=RequestMethod.POST)` | 返回对象即 JSON | |16 | 跨域 | `@CrossOrigin(origins="*") @RequestMapping("/api")` | 可放在类或方法 | |17 | 安全 | `@PreAuthorize("hasRole('ADMIN')") @RequestMapping("/admin")` | Spring Security | |18 | 异步 | `@RequestMapping("/async") public Callable<String> async()` | 返回 `Callable` / `DeferredResult` | |19 | 响应式 | `@RequestMapping("/flux") public Flux<Event> stream()` | WebFlux 场景 | |20 | Swagger 文档 | `@Operation(summary="创建用户") @RequestMapping(value="/users", method=POST)` | springdoc-openapi | >[info]四、易踩的坑 - 类级别 + 方法级别路径拼接时,注意 `/` 重复或缺失: 类:`@RequestMapping("/api/v1")` + 方法:`@RequestMapping("/users")` ⇒ 最终 `/api/v1/users` - 若 `method` 不指定,则 **所有 HTTP 方法** 都能命中,容易引发安全隐患。 - 同时声明 `consumes` 和 `produces` 时,顺序无影响,但都需匹配。 - 老项目升级 Spring Boot 3 后,`@RequestMapping` 默认路径匹配策略由 AntPathMatcher → PathPatternParser,通配符写法保持一致,但性能更优。 - 若在同一个类中同时出现 `@RequestMapping("/users")` 与 `@GetMapping("/users")`,后者更精确优先。 >[info]五、速查口诀 “RequestMapping 是根,路径方法头信息;类级前缀方法级细,多路径多方法都支持;consumes 管接收,produces 管返回;不写 method 全收,安全规范要记牢。”