java - Guice 多重绑定(bind)实例获得不同的依赖实例

标签 java dependency-injection guice

我对 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)”范围。

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

关于java - Guice 多重绑定(bind)实例获得不同的依赖实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34136824/

相关文章:

java - 在 Java 中向按钮添加 ActionListener

c# - 如何解决.net core中Web API构造函数的依赖关系

c# - 使用通用子类型注册依赖项 - 对于 Mediatr

binding - 使用guice绑定(bind)不同的 map

java - 使用带有 AbstractThreadedSyncAdapter 的 RoboGuice 上下文注入(inject)

java - 为什么从 Java 12 开始 JVM 启动速度更快

java - Spring Boot - Mysql 驱动程序 - JPA - 很长一段时间后,服务器运行发布请求显示无法打开 JPA EntityManager 进行事务

java - 将集合转换为数组的最简单方法?

javascript - 不断出现 AngularJS 模块不可用的情况 (ASP.NET 5)

java - 使用 Dagger 2 的自定义注解拦截器