【问题标题】:How can I get name of the Feign client?如何获取 Feign 客户端的名称?
【发布时间】:2026-01-10 11:00:01
【问题描述】:

我有简单的界面:

public interface ServiceClient {
  String REFRESH_ENDPOINT = "/admin/refresh";
  ResponseEntity<String> refresh();
}

很少有这样的 FeignClient:

@FeignClient(name = "${ServiceA.name}", configuration = 
FeignConfiguration.class, decode404 = true)
public interface ServiceA extends ServiceClient {

  @PostMapping(path = REFRESH_ENDPOINT)
  ResponseEntity<String> refresh();
}

然后我做:

private final List<ServiceClient> services;
...
services.parallelStream()
            .collect(Collectors.toMap(s-> s.getClass().getName(), s-> s.refresh().getStatusCode()));

如何获取 Feign 客户端的名称? getClass().getName() 给了我Proxy154。我宁愿不在我拥有的每个 FeignClient 中创建静态字段。

【问题讨论】:

    标签: java spring spring-boot spring-cloud


    【解决方案1】:

    您可以使用 AopProxyUtils。

    services.parallelStream()
                .collect(Collectors.toMap(s-> 
                      AopProxyUtils.proxiedUserInterfaces(greetingClient)[0].getName(), 
                      s-> s.refresh().getStatusCode()));  
    

    不确定是要类名还是 @FeignClient 注释中的名称。如果你想要Annotation中的名字,那么你可以像这样得到它

    Class<?>[] classes = AopProxyUtils.proxiedUserInterfaces(greetingClient);
    FeignClient annotation = classes[0].getAnnotation(FeignClient.class);
    System.out.println(annotation.name());
    

    【讨论】:

    • 没用。仍然收到{"com.sun.proxy.$Proxy154"="OK", "com.sun.proxy.$Proxy155"="OK", "com.sun.proxy.$Proxy156"="OK"}
    • 两个“编辑”解决方案均产生:java.lang.ClassCastException: com.sun.proxy.$Proxy155 cannot be cast to org.springframework.aop.framework.Advised
    • 编辑了我的答案结帐。不知道要类名还是@FeignClient注解中的名字
    • 现在更近了;-) 但它仍然给出:${ServiceA.name}。所以我们需要提取propertyKey,我的意思是"ServiceA.name"并使用env.getProperty("ServiceA.name")
    最近更新 更多