SpringBoot 中 @RequestMapping 及衍生注解的全面解析与实践

在 SpringBoot 开发中,控制器(Controller)是处理 HTTP 请求的核心组件,而@RequestMapping及其衍生注解则是构建 RESTful API 的基础。本文将从注解的工作原理、使用场景到高级特性,全面解析这些注解的用法,帮助开发者写出更优雅、更符合 REST 规范的接口。

一、@RequestMapping 注解的核心作用

@RequestMapping是 Spring MVC 中用于映射 HTTP 请求到控制器方法的核心注解,它可以标注在类上或方法上,具有以下核心功能:

  1. 映射 URL 路径到控制器方法
  1. 限制请求方法(GET、POST 等)
  1. 限制请求参数
  1. 限制请求头
  1. 定义请求媒体类型

基本使用示例

@RestController
@RequestMapping("/api/users") // 类级别映射
public class UserController {
    
    // 方法级别映射
    @RequestMapping(method = RequestMethod.GET)
    public List<User> getAllUsers() {
        // 业务逻辑
    }
}

上述代码中,类上的@RequestMapping("/api/users")定义了基础路径,方法上的注解则进一步指定了处理 GET 请求,因此该方法将处理GET /api/users请求。

二、HTTP 方法特定的衍生注解

为了简化常用 HTTP 方法的映射,Spring 提供了一系列@RequestMapping的衍生注解,这些注解在功能上等价于指定了method属性的@RequestMapping,但使代码更具可读性。

1. @GetMapping

用于处理 HTTP GET 请求,等价于@RequestMapping(method = RequestMethod.GET)。

典型应用场景:查询资源、获取数据

@GetMapping("/{id}")
public ResponseEntity<User> getUserById(@PathVariable Long id) {
    User user = userService.findById(id);
    return ResponseEntity.ok(user);
}

2. @PostMapping

用于处理 HTTP POST 请求,等价于@RequestMapping(method = RequestMethod.POST)。

典型应用场景:创建新资源

@PostMapping
public ResponseEntity<User> createUser(@RequestBody @Valid User user) {
    User savedUser = userService.save(user);
    URI location = ServletUriComponentsBuilder
        .fromCurrentRequest()
        .path("/{id}")
        .buildAndExpand(savedUser.getId())
        .toUri();
    return ResponseEntity.created(location).body(savedUser);
}

3. @PutMapping

用于处理 HTTP PUT 请求,等价于@RequestMapping(method = RequestMethod.PUT)。

典型应用场景:全量更新资源

@PutMapping(
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

java小吕布

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值