在 spring boot 中,如果接口只处理 get 请求,直接使用 @getmapping;如果需要同时支持多种 http 方法或保持通用性,使用 @requestmapping。两者本质相同,@getmapping 是 @requestmapping(method = requestmethod.get) 的简化写法,选择取决于代码简洁性与扩展性的权衡。

@GetMapping 的具体用法与适用场景
当明确只需要处理 GET 请求时,使用 @GetMapping 能让代码意图更清晰且更简洁。它直接映射到 HTTP GET 方法,无需指定 method 属性,减少了样板代码。

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@GetMapping("/users")
public String getUsers() {
return "GET request handled";
}
}
上述代码定义了一个简单的 REST 接口,仅响应 GET 请求。访问 /users 端点时,Spring MVC 会调用 getUsers() 方法并返回字符串。这种写法适合纯查询接口,避免误用 POST 或 PUT 方法。
@RequestMapping 的多方法支持与配置灵活性
当接口需要支持多种 HTTP 方法(如 GET 和 POST)或需要更精细的路径匹配时,@RequestMapping 是更好的选择。它可以指定多个 method,也可以结合 path、params 等属性进行复杂路由配置。

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/data")
public class DataController {
@RequestMapping(value = "/items", method = {RequestMethod.GET, RequestMethod.POST})
public String handleData() {
return "GET or POST handled";
}
}
该示例展示了 @RequestMapping 如何在一个端点上同时处理 GET 和 POST 请求。通过 method 属性指定支持的 HTTP 方法,提高了接口的灵活性。适用于需要统一入口但不同方法有不同逻辑的场景。
基于 /users 端点的输入条件验证行为
对于 /users 端点,若传入非 GET 请求(如 POST),@GetMapping 会直接拒绝并返回 405 Method Not Allowed,而 @RequestMapping 若未指定 method 则可能默认接受所有方法。因此,在使用 @GetMapping 时,需确保客户端严格遵循 HTTP 规范,否则将触发错误响应。











