I use com.google.inject:guice
. In my project, I included a dependency that have a module (a class that extends com.google.inject.AbstractModule
) that defines a MapBinder
like that
public class ParentGuiceModule extends AbstractModule {
@Override
protected void configure() {
MapBinder.newMapBinder(binder(), TypeLiteral.get(String.class), TypeLiteral.get(SomeModuleClass.class));
...
}
}
In my module class, I want to get that MapBinder
and add new bindings to it. I mean I want to write something like that:
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);
}
}
How can I do that? I can not change the parent module.
I looked into MapBinder
class, seems it does not have any methods to get already installed MapBinder
.
This is exactly what MapBinder is designed for—after all, if you knew everything that was going to be inside a MapBinder from within a single Module, you could just write @Provides Map<Foo, Bar>
or bind(new TypeLiteral<Map<Foo, Bar>>(){})
and be done with it.
From the MapBinder top-level docs:
Contributing mapbindings from different modules is supported. For example, it is okay to have both CandyModule and ChipsModule both create their own
MapBinder<String, Snack>
, and to each contribute bindings to the snacks map. When that map is injected, it will contain entries from both modules.
Don't be discouraged by the name newMapBinder
: As long as you have the exact same parameters to newMapBinder
and have both of your Modules installed in the same Injector, you will wind up with one Map that contains bindings from both modules.