我对 Guice 还很陌生,目前有点陷入困境。
我正在用 Java 开发一个小游戏的后端。我想用 Guice 动态注入(inject)游戏系统,为此我使用多重绑定(bind):
private class InstanceModule extends AbstractModule {
@Override
protected void configure() {
bind(GameInstance.class).to(GameInstanceImplementation.class);
bind(EntityManager.class).to(EntityManagerImplementation.class);
bind(EventBus.class).to(EventBusImplementation.class);
bind(MessageBroker.class).toInstance(broker);
Multibinder<GameSystem> systemBinder = Multibinder.newSetBinder(binder(), GameSystem.class);
for (Class<? extends GameSystem> systemClass : systemsConfig) {
systemBinder.addBinding().to(systemClass);
}
}
}
systemsConfig
只是我想要加载游戏的 GameSystem
的类列表。
在我的 GameInstanceImplementation.class
中,我像这样注入(inject)使用的 GameSystems
:
@Inject
public void setSystems(Set<IPMSystem> systems) {
this.systems = systems;
}
我得到的 GameInstance 是这样的:
GameInstance instance = injector.getInstance(GameInstance.class);
我这样做是因为每个 GameSystem
都有不同的依赖项,有些只需要 EntityManager
,有些需要 EventBus
等等上。
现在似乎每个 GameSystem
都有不同的 EventBus
、EntityManager 等......所以它们当然无法相互通信。
我期望每个 GameSystem
都能获得绑定(bind)依赖项的相同实例。
我在这里缺少什么?
提前致谢, 弗罗什法纳蒂卡
最佳答案
默认情况下,Guice 每次创建对象时都会创建每个依赖项的新实例。如果您想更改该行为,并获得对象之间共享的一些依赖项,那么您需要将这些依赖项放入不同的范围中。
所以,而不是...
bind(EventBus.class).to(EventBusImplementation.class);
你会做类似的事情
bind(EventBus.class).to(EventBusImplementation.class)
.in(Singleton.class);
然后 Guice 只会创建一个 EventBus 实现的单个实例,并且任何需要 EventBus 作为依赖项的东西都会被赋予该单独的实例。
值得注意的是,Guice 在这方面的行为与 Spring 不同。 Spring DI 默认将所有 bean 视为单例。 Guice 的默认值更类似于 Spring 所谓的“原型(prototype)”范围。
关于java - Guice 多重绑定(bind)实例获得不同的依赖实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34136824/