如何将一个实现与Google Guice的几个接口绑定?

时间:2011-01-25 09:43:25

标签: java dependency-injection guice

我需要绑定一个类作为两个接口的实现。它应该绑定在单一范围内。

我做了什么:

bind(FirstSettings.class).
    to(DefaultSettings.class).
    in(Singleton.class);
bind(SecondSettings.class).
    to(DefaultSettings.class).
    in(Singleton.class);

但是,显然,它会导致创建两个不同的实例,因为它们被绑定到不同的键。

我的问题是我该怎么做?

3 个答案:

答案 0 :(得分:53)

Guice的维基有a documentation about this use case

基本上,这就是你应该做的:

// Declare that the provider of DefaultSettings is a singleton
bind(DefaultSettings.class).in(Singleton.class);

// Bind the providers of the interfaces FirstSettings and SecondSettings
// to the provider of DefaultSettings (which is a singleton as defined above)
bind(FirstSettings.class).to(DefaultSettings.class);
bind(SecondSettings.class).to(DefaultSettings.class);

没有必要指定任何其他类:只需考虑Provider s,答案就会很自然。

答案 1 :(得分:4)

我找到的解决方案是:

bind(FirstSettings.class).
    to(DefaultSettings.class).
    in(Singleton.class);
bind(SecondSettings.class).
    to(FirstSettings.class).
    in(Singleton.class);

它适用于我的情况,因为SecondSettings扩展了FirstSettings。

答案 2 :(得分:2)

因此,DefaultSettingsFirstSettingsSecondSettings的实现,即:

public class DefaultSettings implements FirstSettings, SecondSettings
{
}

假设您有一个课程EngineAEngineB

public class EngineA
{
    @Inject
    private FirstSettings settings;
}

public class EngineB
{
    @Inject
    private SecondSettings settings;
}

并且您希望注入相同的实现。

您可以声明接口DefaultSettingsInterface

public interface DefaultSettingsInterface extends FirstSettings, SecondSettings
{
}

并制作DefaultSettings工具DefaultSettingsInterface

public class DefaultSettings implements DefaultSettingsInterface
{
}

然后配置可能是:

bind(FirstSettings.class).to(DefaultSettingsInterface.class);
bind(SecondSettings.class).to(DefaultSettingInterface.class);
bind(DefaultSettingsInterface.class).to(DefaultSettings.class).in(Singleton.class);