简体   繁体   中英

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.

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.

A solution, but unfortunatelly not using annotations, would be:

enum Level 
{
    NORMAL, FANCY, DEBUGGING;

    static final Level defaultLevel = FANCY; //put your default here
}

then define module like this:

public class DefaultLevelModule extends AbstractModule 
{
    @Override public void configure() 
    {
        bind(Level.class).toInstance(Level.defaultLevel);
    }
}

It's the issue 295 and looks like a very trivial bug.

I've patched it for myself and maybe one day somebody there will fix this very old issue, too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM