在 Spring Cloud 微服務架構中,使用 Feign 客戶端呼叫服務端 REST API 時,若介面方法參數使用 @RequestParam 但未明確指定 value 屬性,啟動專案會拋出異常。
@RequestMapping(value = "/phone")
public ResponsePhone getPhone(@RequestParam String uid, @RequestParam List<String> orderidlist) {
// 業務邏輯
}
@RequestMapping(value = "/phone")
ResponsePhone getPhone(@RequestParam String uid, @RequestParam List<String> orderidlist);
Caused by: java.lang.IllegalStateException: Method parameter must have a name... Feign requires explicit parameter names when using @RequestParam
Feign 預設不依賴編譯時參數名稱保留 (-parameters 編譯選項)。當 @RequestParam 未指定 value 時,Feign 無法解析參數名稱,導致無法構建請求 URL 參數。
@RequestMapping(value = "/phone")
ResponsePhone getPhone(
@RequestParam(value = "uid") String uid,
@RequestParam(value = "orderidlist") List<String> orderidlist
);
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<compilerArgs>
<arg>-parameters</arg>
</compilerArgs>
</configuration>
</plugin>
配合 Lombok @AllArgsConstructor 或手動建構子可保留參數名。
public class PhoneRequest {
private String uid;
private List<String> orderidlist;
// getter/setter
}
@GetMapping("/phone")
ResponsePhone getPhone(@SpringQueryMap PhoneRequest request);
@SpringQueryMap 或 @RequestBody| 參數類型 | 註解 | 說明 |
|---|---|---|
| 基本類型/String | @RequestParam("name") | URL 查詢參數 |
| List/Set/Array | @RequestParam("ids") | 重複參數名: ids=1&ids=2 |
| POJO | @SpringQueryMap / @ModelAttribute | 扁平化為多個查詢參數 |
| 複雜物件 | @RequestBody | JSON 請求體 (需 POST/PUT) |
| Header | @RequestHeader("token") | HTTP Header |
| Path Variable | @PathVariable("id") | URL 路徑變量 |
Feign 參數綁定問題是 Spring Cloud 微服務開發中極高頻的坑。遵循「明確優於隱含」原則,始終為 @RequestParam 指定 value,能節省大量排查時間,提升團隊開發效率。