Guice 多重绑定实例获得不同的依赖实例

Guice multibinding-instances get different dependency-instances

我是 Guice 的新手,现在有点卡住了。

我正在 Java 开发一个小游戏的后端。我想使用 Guice 动态注入游戏系统,为此我使用了多重绑定:

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 中,我像这样注入使用过的 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 都会获得相同的绑定依赖实例。

我在这里错过了什么?

提前致谢, Froschfanatika

默认情况下,每次创建对象时,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' 范围。

https://github.com/google/guice/wiki/Scopes