Feign Client手动添加方法后无法代理继承接口方法的解决方案咨询
问题解决:Feign Client继承接口后默认方法不被代理的修复方案
问题原因
模块B的AccountsClient因自定义了getAccounts()方法,导致Spring Cloud Feign仅代理子接口显式定义的方法;而父接口AccountsApi中的searchForAccounts()带有默认实现(返回501 NOT_IMPLEMENTED),Feign会直接调用该默认实现,而非生成远程请求代理。
解决方案
方案1:显式重写父接口方法
在模块B的AccountsClient中,显式重写需要代理的父接口方法,保留原注解但移除默认实现,让Feign识别并生成代理:
// module B @FeignClient(name = "accountClient", url = "${accounts.internal.api.url}") public interface AccountsClient extends AccountsApi { @GetMapping ResponseEntity<Accounts> getAccounts(@RequestParam("customerXRef") String customerXRef); // 显式重写父接口方法,移除默认实现 @Override @RequestMapping( method = RequestMethod.GET, value = "/accounts", produces = {"application/json"} ) ResponseEntity<Accounts> searchForAccounts(@RequestParam(value = "accountIds", required = false) List<String> accountIds); }
方案2:修改OpenAPI代码生成配置
调整OpenAPI Codegen的生成规则,让生成的AccountsApi接口方法为无默认实现的抽象方法,这样所有Feign Client继承后会自动代理所有方法:
- 如果使用Maven插件,在配置中添加
defaultMethod=false:
<plugin> <groupId>org.openapitools</groupId> <artifactId>openapi-generator-maven-plugin</artifactId> <version>最新版本</version> <configuration> <!-- 其他配置 --> <defaultMethod>false</defaultMethod> </configuration> </plugin>
生成后的AccountsApi方法会变为抽象方法:
@Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "Account Information", description = "Search and view customer accounts") public interface AccountsApi { default Optional<NativeWebRequest> getRequest() { return Optional.empty(); } @RequestMapping( method = RequestMethod.GET, value = "/accounts", produces = {"application/json"} ) ResponseEntity<Accounts> searchForAccounts( @Parameter(name = "accountIds", description = "Comma separated list of account ids", in = ParameterIn.QUERY) @Valid @RequestParam(value = "accountIds", required = false) List<String> accountIds ); }
注意事项
- 不要开启
feign.default-method-handler-enabled=true配置,该配置是让Feign直接调用接口默认方法,而非生成远程请求代理,会加重问题。
内容的提问来源于stack exchange,提问作者Sergey Tsypanov
相关产品推荐
相关产品推荐

