1. 基本概念
@RequestMapping 是Spring MVC中最基础的请求映射注解,可以处理所有HTTP方法(GET、POST、PUT、DELETE等)。
@GetMapping 是Spring 4.3引入的组合注解,专门用于处理HTTP GET请求,本质上是 @RequestMapping(method = RequestMethod.GET)
的简化写法。
2. 主要区别
语法简洁性
// 使用 @RequestMapping
@RequestMapping(value = "/users", method = RequestMethod.GET)
public List<User> getUsers() {
return userService.getAllUsers();
}
// 使用 @GetMapping(更简洁)
@GetMapping("/users")
public List<User> getUsers() {
return userService.getAllUsers();
}
HTTP方法支持
- @RequestMapping: 支持所有HTTP方法,需要通过
method
属性指定 - @GetMapping: 只支持GET请求,无需指定method属性
类型安全
- @RequestMapping: 如果忘记指定method,默认支持所有HTTP方法
- @GetMapping: 类型安全,明确表示只处理GET请求
3. 其他相似的组合注解
Spring还提供了其他HTTP方法的组合注解:
@PostMapping
=@RequestMapping(method = RequestMethod.POST)
@PutMapping
=@RequestMapping(method = RequestMethod.PUT)
@DeleteMapping
=@RequestMapping(method = RequestMethod.DELETE)
@PatchMapping
=@RequestMapping(method = RequestMethod.PATCH)
4. 使用建议
- 优先使用具体的组合注解:如@GetMapping、@PostMapping等,代码更清晰
@RequestMapping适用场景:
- 类级别的基础路径映射
- 需要处理多种HTTP方法的场景
- 需要复杂配置的场景
5. 实际示例
@RestController
@RequestMapping("/api/users") // 类级别基础路径
public class UserController {
@GetMapping // 处理 GET /api/users
public List<User> getAllUsers() {
return userService.findAll();
}
@GetMapping("/{id}") // 处理 GET /api/users/{id}
public User getUserById(@PathVariable Long id) {
return userService.findById(id);
}
@PostMapping // 处理 POST /api/users
public User createUser(@RequestBody User user) {
return userService.save(user);
}
// 如果需要同时处理多种方法
@RequestMapping(value = "/batch", method = {RequestMethod.POST, RequestMethod.PUT})
public ResponseEntity<String> batchOperation() {
return ResponseEntity.ok("Batch operation completed");
}
}
总结:@GetMapping是@RequestMapping的特化版本,专门用于GET请求,代码更简洁、类型更安全。在实际开发中,建议优先使用@GetMapping等具体的HTTP方法注解。