题目
Spring MVC中@RequestMapping和@GetMapping注解的区别与用法
信息
- 类型:问答
- 难度:⭐
考点
Spring MVC注解,HTTP方法映射,请求路径配置
快速回答
主要区别:
- @RequestMapping:通用请求映射,需手动指定HTTP方法(如method=RequestMethod.GET)
- @GetMapping:专门处理GET请求的快捷注解,无需指定method
最佳实践:
- 优先使用
@GetMapping等专用注解简化代码 - 复杂场景(如多方法支持)用
@RequestMapping
1. 核心区别
@RequestMapping 是通用请求映射注解:
- 可配置
method属性支持所有HTTP方法(GET/POST/PUT等) - 示例:
@RequestMapping(value="/user", method=RequestMethod.GET)
@GetMapping 是组合注解(元注解):
- 专用于处理HTTP GET请求
- 等价于
@RequestMapping(method=RequestMethod.GET) - 示例:
@GetMapping("/user")
2. 代码示例对比
// 使用@RequestMapping处理GET请求
@Controller
@RequestMapping("/old")
public class OldController {
@RequestMapping(value = "/info", method = RequestMethod.GET)
public String getInfo() {
return "info";
}
}
// 使用@GetMapping(推荐)
@Controller
@RequestMapping("/new")
public class NewController {
@GetMapping("/info") // 更简洁
public String getInfo() {
return "info";
}
}3. 最佳实践
- 优先专用注解:
@GetMapping,@PostMapping,@PutMapping等使代码更简洁 - 类级路径:在类上使用
@RequestMapping定义公共路径前缀 - 方法级注解:方法上使用专用注解处理具体HTTP方法
4. 常见错误
- 冲突映射:相同路径+相同HTTP方法会导致启动报错
- 遗漏method属性:
@RequestMapping不指定method时默认接受所有HTTP请求 - 路径重复:类级和方法级路径拼接时注意避免多余斜杠(如
@RequestMapping("/user")+@GetMapping("info")→ /userinfo)
5. 原理说明
Spring MVC通过HandlerMapping组件解析注解:
- 扫描所有Controller中的注解
- 建立URL路径 → 处理方法的映射关系
- 收到请求时匹配对应的
@Controller方法执行
@GetMapping本质是元注解:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@RequestMapping(method = RequestMethod.GET) // 核心实现
public @interface GetMapping { ... }6. 扩展知识
- 路径变量:配合
@PathVariable使用(如@GetMapping("/user/{id}")) - 参数绑定:
@RequestParam获取查询参数 - RESTful设计:专用注解能更清晰表达API语义(GET=获取资源,POST=创建资源)