Reputation: 1281
I have got below code in main class
public ABCImpl() {
Injector injector = Guice.createInjector(new SomeModule());
this.config = injector.getInstance(SomeConfig.class);
SomeModule has other modules in it installed like
public class SomeModule extends AbstractModule {
@Override
protected void configure() {
install(new SomeOtherModule());
install(new AndAnotherModule());
}
}
SomeOtherModule module belongs to some different jar and it has a provider implementation.
@ProvidesIntoOptional(ProvidesIntoOptional.Type.DEFAULT)
public XYZ getXYZ() {
return new XYZ();
}
Now I want to override this default inside SomeModule or create a different module to be installed based on values in config
@ProvidesIntoOptional(ProvidesIntoOptional.Type.DEFAULT)
public XYZ getXYZDifferentWay() {
return new XYZ(someparam);
}
How can I achieve this. My only goal is if some value on config is true then I should get different XYZ otherwise keep things as it is. This could be useful in cases where you need default resource connection but in local machine may be I can use mock resource.
Upvotes: 3
Views: 3617
Reputation: 140554
Literally just install them conditionally:
if (condition) {
install(new SomeOtherModule());
} else {
install(new AndAnotherModule());
}
Or, if you want AndAnotherModule
to override the bindings in SomeOtherModule
, use Modules.override
:
Module module = new SomeOtherModule();
if (condition) {
module = Modules.override(module).with(new AndAnotherModule());
}
install(module);
Or, if you want to use configuration from another guice binding:
// In SomeOtherModule
@Provides @FromSomeOtherModule
public XYZ getXYZ() { ... }
// In AndAnotherModule
@Provides @FromAndAnotherModule
public XYZ getXYZ() { ... }
// In a module which "picks" between the two:
@ProvidesIntoOptional(ProvidesIntoOptional.Type.DEFAULT)
public XYZ provideBasedOnCondition(
@SomeQualifier boolean condition,
@FromSomeOtherModule XYZ fromSomeOtherModule,
@FromAndAnotherModule XYZ fromAndOtherModule) {
return condition ? fromSomeOtherModule : fromAndOtherModule;
}
where @FromSomeOtherModule
, @FromAndAnotherModule
and @SomeQualifier
are suitable binding annotations.
Upvotes: 3