使用 guice 中的地图初始化 mapbinder

Initializing mapbinder with a map in guice

我正在尝试将地图作为 bean 注入到我的 class (Helper.java) 之一中。我计划在绑定 Helper.javaHelperModule 中创建此地图。

我相信为了将地图作为 bean 注入,我需要使用 MapBinder。然后填充 binderOfMap 中的所有绑定,然后最终使用我的 class 中的地图。

public class HelperModule extends AbstractModule {

    @Override
    protected void configure() {
        log.info("Configuring the helper module.");
        configureHelper();

        final MapBinder<String, String> binderOfMap =
                MapBinder.newMapBinder(binder(), new TypeLiteral<String> () {},
                        new TypeLiteral<String>() {},
                        Names.named("CustomMap"));

                Map<String, String> myFieldsMap = 
                           myDependency.getCustomMap(SomeConstants);

        for (Map.Entry<String, String> entry: myFieldsMap.entrySet()) {
          binderOfMap.addBinding(entry.getKey()).toInstance(entry.getValue());
        }

    private void configureHelper() {
        bind(Helper.class).in(Scopes.SINGLETON);
    }
}

我是否必须遍历整个 myFieldsMap 才能添加到 binderOfMap?或者,有没有办法用 myFieldsMap 初始化 binderOfMap

此外,我现在可以在我的 class 中直接注入带有 @Named 注释 ("CustomMap")Map<String,String> 吗?

根据MapBinder documentation, only addBinding方法在映射中添加一个新条目,一次取一个键。

要迭代 myFieldsMap 您可以使用流,例如

myFieldsMap.forEach((key, value) -> binderOfMap.addBinding(key).toInstance(value));

Helper 构造函数可以像这样

@Inject
public Helper(@Named("CustomMap") Map<String, String> map) {...}

TypeLiteral 表示泛型类型 T,对于您的情况,您可以简单地使用

MapBinder.newMapBinder(binder(), String.class, String.class, Names.named("CustomMap"));