我用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
。
这正是MapBinder的设计目标 - 毕竟,如果你从单个模块中知道将在MapBinder中的所有内容,你可以编写@Provides Map<Foo, Bar>
或bind(new TypeLiteral<Map<Foo, Bar>>(){})
并完成它。
支持从不同模块贡献地图绑定。例如,可以让CandyModule和ChipsModule都创建自己的
MapBinder<String, Snack>
,并为每个提供绑定到小吃地图。注入该映射时,它将包含来自两个模块的条目。
不要被newMapBinder
这个名称所劝阻:只要你有与newMapBinder
完全相同的参数并且你的两个模块都安装在同一个Injector中,你就会得到一个包含两个模块绑定的Map。