我需要绑定(bind)一个类作为两个接口(interface)的实现。它应该绑定(bind)在一个单例范围内。
我做了什么:
bind(FirstSettings.class).
to(DefaultSettings.class).
in(Singleton.class);
bind(SecondSettings.class).
to(DefaultSettings.class).
in(Singleton.class);
但是,很明显,这会导致创建两个不同的实例,因为它们绑定(bind)到不同的键。
我的问题是我该怎么做?
最佳答案
Guice 的 wiki 有 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
来考虑,答案自然而然。
关于java - 如何使用 Google Guice 将一个实现绑定(bind)到几个接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4791908/