@RequestMapping 是 Spring MVC 顶层核心请求映射注解,也是 Spring Boot 中请求路由的基础组件。它的核心作用是将 HTTP 请求与控制器的类 / 方法精准绑定,实现请求的分发处理。 所有简化型注解(@GetMapping/@PostMapping 等)均基于该注解实现,是开发 Web 接口、RESTful API 的基石。
双重作用域:支持类级别(统一父路径)+ 方法级别(具体子路径),嵌套组合形成完整请求 URL
全 HTTP 方法兼容:支持 GET/POST/PUT/DELETE/HEAD 等所有标准 HTTP 请求方式
精细化匹配:可通过路径、请求方法、参数、请求头、数据格式等条件精准筛选请求
通用基础:是所有快捷映射注解的父注解,扩展性极强
@RequestMapping 支持多属性精细化配置请求匹配规则
// 完整配置写法
@RequestMapping(
value = "/url路径",
method = RequestMethod.请求方式,
params = "请求参数规则",
headers = "请求头规则",
consumes = "接收的请求数据类型",
produces = "返回的响应数据类型"
)这是 @RequestMapping 最实用的用法,实现接口路径规范化:
公共父路径
为控制器下所有接口统一前缀,简化重复代码、统一接口规范
@RestController
@RequestMapping("/api/users") // 所有接口的公共父路径
public class UserController { }具体子路径
定义单个接口的子路径,与类路径拼接为完整访问地址
// 完整路径:/api/users/list
@RequestMapping(value = "/list", method = RequestMethod.GET)
public List<User> listUsers() { ... }企业开发首选
为简化代码、提升可读性,Spring 提供了 @RequestMapping 的专用派生注解,语义更清晰、代码更简洁,是实际开发的标准用法:
<dependencies>
<!-- Spring Web 核心依赖,包含@RequestMapping所有功能 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>Spring Boot 标准写法
import org.springframework.web.bind.annotation.*;
import java.util.List;
// @RestController = @Controller + @ResponseBody(自动返回JSON)
@RestController
// 类级别:统一父路径
@RequestMapping("/api/test")
public class TestController {
// 1. 基础GET请求:完整路径 /api/test/hello
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String sayHello() {
return "Hello Spring Boot!";
}
// 2. 参数匹配:必须携带name参数 /api/test/params?name=test
@RequestMapping(value = "/params", method = RequestMethod.GET, params = "name")
public String testParams(@RequestParam String name) {
return "接收参数:" + name;
}
// 3. 返回JSON数组:/api/test/tasks
@RequestMapping(value = "/tasks", method = RequestMethod.GET)
public List<String> getTasks() {
return List.of("学习Spring", "开发接口", "单元测试");
}
// 4. 接收JSON请求体:/api/test/user
@RequestMapping(
value = "/user",
method = RequestMethod.POST,
consumes = "application/json",
produces = "application/json"
)
public User createUser(@RequestBody User user) {
return user;
}
}
// 测试实体类
class User {
private Long id;
private String username;
// 自动生成getter/setter
}优先使用派生注解:用 @GetMapping 替代原生 @RequestMapping,语义更清晰
类级别统一前缀:强制使用 @RequestMapping 定义公共路径,规范接口
严格指定请求方法:禁止省略 method,避免接口被非法调用
RESTful 规范:路径使用名词复数(/users),禁止使用动词(/getUser)
配合 @RestController:Spring Boot 中无需单独写 @Controller+@ResponseBody
@RequestMapping 是 Spring 路由的顶层注解,所有快捷注解都基于它实现
支持类 + 方法两级路径嵌套,可通过多属性精细化匹配请求
实际开发优先使用 @GetMapping/@PostMapping 等派生注解
配合 @RestController 是 Spring Boot 开发 RESTful API 的标准方案