如何安装MapBinder以向其中添加其他绑定

问题描述 投票:0回答:1

我用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

java guice
1个回答
1
投票

这正是MapBinder的设计目标 - 毕竟,如果你从单个模块中知道将在MapBinder中的所有内容,你可以编写@Provides Map<Foo, Bar>bind(new TypeLiteral<Map<Foo, Bar>>(){})并完成它。

来自MapBinder top-level docs

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

不要被newMapBinder这个名称所劝阻:只要你有与newMapBinder完全相同的参数并且你的两个模块都安装在同一个Injector中,你就会得到一个包含两个模块绑定的Map。

© www.soinside.com 2019 - 2024. All rights reserved.