简体   繁体   English

Guice中的一个类的多个提供者

[英]Multiple provider for a class in Guice

I have a Guice whose constructor accept an injected argument: 我有一个Guice,其构造函数接受一个注入的参数:

@Singleton
public class MyClass {
    private MyConfiguration myConfiguration;

    @Inject
    public MyClass(MyConfiguration myConfiguration) {
        this.myConfiguration = myConfiguration;
    }
}

Now, I want to be able to inject the argument depends on the environment I run this. 现在,我希望能够注入参数取决于我运行的环境。 In Test, I want to inject a MyConfiguration object while in production I want to inject another object. 在Test中,我想在生产中注入一个MyConfiguration对象,我想要注入另一个对象。

I have got two providers for MyConfiguration. 我有两个MyConfiguration提供程序。 The MyConfigurationProvider reads a external configuration file and get the config from there. MyConfigurationProvider读取外部配置文件并从那里获取配置。 The MyConfigurationTestProvider just hard code all the settings. MyConfigurationTestProvider只是对所有设置进行硬编码。

I don't know how to config this though. 我不知道怎么配置这个。 I tried to do a binding in the Guice module like: 我试图在Guice模块中进行绑定,如:

public class MyGuiceModule extends AbstractModule {
    @Override
    protected void configure() {
       bind(MyConfiguration.class).toProvider(MyConfigurationProvider.class).in(Singleton.class);
    }
}

And in the Guice module of the test, use: 在测试的Guice模块中,使用:

public class MyGuiceTestModule extends AbstractModule {
    @Override
    protected void configure() {
        install(new MyGuiceModule());
        bind(MyConfiguration.class).toProvider(MyConfigurationTestProvider.class).in(Singleton.class);
    }
}

But this gave me an error of binding more than one provider. 但这给了我绑定多个提供商的错误。

My question is that how I can use different provider for same object depends on environment? 我的问题是,如何为同一个对象使用不同的提供程序取决于环境?

Many thanks. 非常感谢。

Yes, Guice modules cannot contain multiple bindings with the same key by default. 是的,Guice模块默认情况下不能包含多个具有相同键的绑定。 However, you can use override feature of modules when creating your injector. 但是,您可以在创建进样器时使用模块的覆盖功能。 This feature was designed exactly for this purpose. 此功能专为此目的而设计。

Remove install() thing from your test module and create an injector for your test environment like this: 从测试模块中删除install() ,并为您的测试环境创建一个注入器,如下所示:

Injector injector = Guice.createInjector(Modules.override(new MyGuiceModule()).with(new MyGuiceTestModule()));

With this your binding for MyConfiguration from test module will replace the binding from production module. 有了这个,你从测试模块绑定MyConfiguration将取代生产模块的绑定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM