我有一个 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();
}
Service
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
成员变量在MyService
属于类型
HardCodedTarget(类型=FoorResource,url=http://foo-service http://foo-service)
根据 IntelliJ 的说法。这是由 Spring Cloud Netflix 框架自动生成的类型,因此会尝试与远程服务进行实际通信。
有没有一种方法可以根据配置设置有条件地覆盖 Feign 接口的实现?