Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify default Enum instance for Guice?

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.

like image 839
maaartinus Avatar asked Dec 29 '22 00:12

maaartinus


1 Answers

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.

like image 200
Boris Pavlović Avatar answered Dec 30 '22 14:12

Boris Pavlović