在SpringBoot中,@GetMapper和@RequestMapping有什么区别?

12 阅读1分钟

 联系:

@RequestMapping:
是一个通用的请求映射注解,支持所有HTTP方法(GET、POST、PUT等)。需要通过method属性显式指定具体的HTTP方法。

例如:

@RequestMapping(value = "/example", method = RequestMethod.GET)
public String example() {
    return "example";
}

@GetMapping
@RequestMapping特化版本,专门用于处理HTTP GET请求。它是Spring 4.3引入的组合注解(@RequestMapping(method = RequestMethod.GET)的简写)。
例如:

@GetMapping("/example")
public String example() {
    return "example";
}

区别:

  • @GetMapping语法更简洁,无需手动指定method属性,直接映射GET请求。
  • @RequestMapping需要显式配置method属性,代码略显冗余。

组合注解:

Spring 还提供了其他类似的特化注解,与@GetMapping风格一致:

  • @PostMapping → 处理POST请求
  • @PutMapping → 处理PUT请求
  • @DeleteMapping → 处理DELETE请求
  • @PatchMapping → 处理PATCH请求

这些注解均基于@RequestMapping实现,但语义更清晰。

 默认行为

  • @RequestMapping
    如果没有指定method属性,默认会映射所有HTTP方法(GET、POST等)。这可能意外导致安全问题或不明确的端点行为。
    例如:
@RequestMapping("/unsafe") // 会响应GET、POST等所有请求!
public String unsafe() {
    return "unsafe";
}

  • @GetMapping
    明确限定为GET请求,避免歧义。

总结

特性@RequestMapping@GetMapping
HTTP方法支持所有方法(需显式配置)仅限GET
代码简洁性冗余(需指定method简洁
语义明确性较低高(专为GET设计)
安全性需手动配置,易遗漏默认安全
适用场景需要支持多HTTP方法的场景仅需处理GET请求的场景