DEBUG.WIKI
PanstarCloud:部署应用,接入 AI,云服务器与 AI 网关
晚安云;香港 CN2 ¥15/月
V.PS:让项目靠近用户,亚太、欧洲、北美 KVM VPS

解决 Spring Cloud Feign 报错 405 Method Not Allowed 传参注解修复

排查 Spring Cloud OpenFeign 客户端调用微服务接口返回 HTTP 405 Method Not Allowed,分析 @RequestParam 与 @SpringQueryMap 导致 GET 降级 POST 问题。

问题现象

微服务 A 通过 OpenFeign 客户端调用微服务 B 的 GET 查询接口时抛出异常:

feign.FeignException$MethodNotAllowed: [405 Method Not Allowed] 
during [GET] to [http://user-service/api/users] [UserClient#getUser(UserDTO)]:
[{"timestamp":"2026-11-15T12:00:00.000+00:00","status":405,"error":"Method Not Allowed"}]

触发根因

在 Spring Cloud OpenFeign 中定义 GET 请求接口时,如果方法入参传入的是一个实体对象(POJO)而未加任何注解,或者使用的是 Spring MVC 常规注解,底层的 Feign 编码器(基于 HttpURLConnection 或 Apache HttpClient)会自动判定只要包含请求体(Body),请求方法就必须强制转为 POST。下游服务由于只配置了 @GetMapping,因此直接返回 405 Method Not Allowed。

解决步骤

1. 将复杂入参对象使用 @SpringQueryMap 注解修饰

Spring Cloud 提供了专门将 POJO 字段扁平化序列化为 URL Query 字符串的注解:

@FeignClient(name = "user-service")
public interface UserClient {
    // 正确写法:使用 @SpringQueryMap 展开为 URL 查询参数
    @GetMapping("/api/users")
    UserVO getUser(@SpringQueryMap UserQueryDTO queryDTO);
}

2. 对基础类型入参务必标注 @RequestParam

对于离散参数,必须显式指明参数名:

@GetMapping("/api/users/detail")
UserVO getUserById(@RequestParam("userId") Long userId);

验证确认

运行集成测试验证跨服务通信:

./mvnw test -Dtest=UserClientTest

测试用例正常通过,Wireshark 或日志中确认实际发出的 HTTP 方法为标准的 GET /api/users?userId=123。