我有一个 Spring Boot 应用程序,它使用 Feign 通过 Eureka 调用外部 Web 服务。我希望能够使用 Feign 接口的模拟实现来运行应用程序,这样我就可以在本地运行应用程序,而不必运行 Eureka 或外部 Web 服务。我曾设想定义一个允许我执行此操作的运行配置,但我正在努力让它发挥作用。问题是无论我尝试什么,Spring 的“魔法”都在为 Feign 接口定义一个 bean。
假装界面
@FeignClient(name = "http://foo-service")
public interface FooResource {
@RequestMapping(value = "/doSomething", method = GET)
String getResponse();
}
服务
public class MyService {
private FooResource fooResource;
...
public void getFoo() {
String response = this.fooResource.getResponse();
...
}
}
我尝试添加一个配置类,如果 Spring 配置文件是“本地”,则有条件地注册一个 bean,但是当我使用该 Spring 配置文件运行应用程序时从未调用过它:
@Configuration
public class AppConfig {
@Bean
@ConditionalOnProperty(prefix = "spring.profile", name = "active", havingValue="local")
public FooResource fooResource() {
return new FooResource() {
@Override
public String getResponse() {
return "testing";
}
};
}
}
在我的服务运行时,FooResource
成员变量 inMyService
是类型
HardCodedTarget(type=FoorResource, url= http://foo-service )
根据 IntelliJ。这是由 Spring Cloud Netflix 框架自动生成的类型,因此会尝试与远程服务进行实际通信。
有没有一种方法可以根据配置设置有条件地覆盖 Feign 接口的实现?