首页 文章

根据环境定义不同的Feign客户端实现

提问于
浏览
2

我有一个Spring启动应用程序,它使用Feign通过Eureka调用外部Web服务 . 我希望能够使用模拟的Feign接口实现来运行应用程序,因此我可以在本地运行应用程序而无需运行Eureka或外部Web服务 . 我曾经想象过定义一个允许我这样做的运行配置,但我很难让它运行起来 . 问题是,无论我尝试什么,Spring“魔法”都会为Feign界面定义一个bean .

Feign interface

@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";
            }
        };
    }
}

在我的服务运行时, MyService 中的 FooResource 成员变量属于类型

HardCodedTarget(type = FoorResource,url = http:// foo-service)

根据IntelliJ . 这是Spring Cloud Netflix框架自动生成的类型,因此尝试实际与远程服务进行通信 .

有没有办法可以根据配置设置有条件地覆盖Feign接口的实现?

1 回答

  • 2

    Spring Cloud Netflix github存储库上发布了相同的问题,一个有用的答案是使用Spring @Profile 注释 .

    我创建了一个没有用 @EnabledFeignClients 注释的替代入口点类,并创建了一个新的配置类来定义我的Feign接口的实现 . 现在,这允许我在本地运行我的应用程序,而无需运行Eureka或任何相关服务 .

相关问题