Reputation: 115
I've my own Guice module and in the configure method, I've provided my own bindings as under -
public void configure() {
MapBinder<String, ExternalDatabaseConnection> m = MapBinder.newMapBinder(binder(), String.class, ExternalDatabaseConnection.class);
m.addBinding("DBServer1").to(ExternalDBServer1Connection.class);
m.addBinding("DBServer2").to(ExternalDBServer2Connection.class);
}
The above is deployed as a web application. I want to let third party providers be able to provide there own implementations and give a jar file for connection class. How do I do that? That is instead of modifying code above to add new binding like below -
m.addBinding("DBServer3").to(ExternalDBServer3Connection.class);
Upvotes: 4
Views: 1495
Reputation: 1741
Contributing mapbindings from different modules is supported.
Check this for more details.
Upvotes: 0
Reputation: 12051
You may combine modules. Here is an example. Let's say you have extenral and internal modules that live separately.
public class InternalModule extends AbstractModule {
@Override
protected void configure() {
MapBinder<String, String> m = MapBinder.newMapBinder(binder(), String.class, String.class);
m.addBinding("DBServer1").toInstance("Value1");
m.addBinding("DBServer2").toInstance("Value2");
}
}
and:
public class ExternalModule extends AbstractModule {
@Override
protected void configure() {
MapBinder<String, String> m = MapBinder.newMapBinder(binder(), String.class, String.class);
m.addBinding("DBServer3").toInstance("Value3");
}
}
Here is an injector based on the combination of the two modules (e.g. this may live in your app and you may implement some simple registration mechanism):
InternalModule moduleInt = new InternalModule();
ExternalModule moduleExt = new ExternalModule();
Module combined = Modules.combine(moduleInt, moduleExt);
Injector injector = Guice.createInjector(combined);
When this injector injects a map, e.g.:
@Inject
private Map<String, String> stringMap;
this map will contain the following values:
{DBServer1=Value1, DBServer2=Value2, DBServer3=Value3}
It is also possible to override modules instead of combining them. In this case external libraries will replace your own implementations.
Hope this helps.
Upvotes: 4