I'd need something like
@DefaultInstance(Level.NORMAL)
enum Level {NORMAL, FANCY, DEBUGGING}
which would make Guice to return Level.NORMAL for the expression
injector.getInstance(Level.class)
There's no such thing like @DefaultInstance. As a workaround I've tried @ProvidedBy with a trivial Provider, but it doesn't work.
Maybe overriding modules could help you. A default level can be configured using AppLevel module:
public class AppModule extends AbstractModule {
@Override
public void configure() {
bind(Level.class).toInstance(Level.NORMAL);
// other bindings
}
}
and a specific one can be configured in a small overriding module:
public class FancyLevelModule extends AbstractModule {
@Override
public void configure() {
bind(Level.class).toInstance(Level.FANCY);
}
}
At the end just create an injector overriding the AppModule with a specific Level config:
public static void main(String[] args) {
Injector injector =
Guice.createInjector(
Modules.override(new AppModule()).with(new FancyLevelModule())
);
System.out.println("level = " + injector.getInstance(Level.class));
}
UPDATE
This problem can be solved in a bit different way. Let's say that Level is used in a class as an injected field:
class Some
{
@Injected(optional = true)
private Level level = Level.NORMAL;
}
A default level will be initialized as part of the creation of instances of Some. If some Guice config module declares some other level it will be optionally injected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With