如何获取已安装的MapBinder以向其中添加其他绑定

时间:2019-04-24 15:38:22

标签: java guice

我使用com.google.inject:guice。在我的项目中,我包含一个依赖项,该依赖项具有一个模块(扩展了com.google.inject.AbstractModule的模块),该模块定义了一个MapBinder

public class ParentGuiceModule extends AbstractModule {    
    @Override
    protected void configure() {
        MapBinder.newMapBinder(binder(), TypeLiteral.get(String.class), TypeLiteral.get(SomeModuleClass.class));
        ...
    }
}

在我的模块类中,我想获取该MapBinder并为其添加新的绑定。我的意思是我想写这样的东西:

public class MyGuiceModule extends AbstractModule {    
    @Override
    protected void configure() {
        MapBinder<String, SomeModuleClass> parentModules = MapBinder.get(binder(), TypeLiteral.get(String.class), TypeLiteral.get(SomeModuleClass.class));
        parentModules.addBinding("MyId").to(MyClass.class);
    }
}    

我该怎么做?我无法更改父模块。

我查看了MapBinder类,似乎它没有任何方法可以安装MapBinder

1 个答案:

答案 0 :(得分:1)

这正是MapBinder设计的目的-毕竟,如果您知道单个模块中所有将在MapBinder中存储的内容,则只需编写@Provides Map<Foo, Bar>bind(new TypeLiteral<Map<Foo, Bar>>(){})即可完成。

来自MapBinder top-level docs

  

支持从不同模块贡献映射绑定。例如,可以使CandyModule和ChipsModule都创建自己的MapBinder<String, Snack>,并为小吃地图贡献绑定。插入该映射后,它将包含两个模块的条目。

不要对名称newMapBinder感到沮丧:只要您拥有与newMapBinder完全相同的参数,并且两个模块都安装在同一个喷油器中,您将获得一个包含两个模块的绑定的地图。

相关问题