How to specify default Enum instance for Guice?

I need something like

@DefaultInstance(Level.NORMAL)
enum Level {NORMAL, FANCY, DEBUGGING}

which made Guice return Level.NORMALfor expression

injector.getInstance(Level.class)

There is no such thing as @DefaultInstance. As a workaround, I tried @ProvidedBywith the trivial one Provider, but it does not work.

+3
source share
3 answers

This is problem 295 and looks like a very trivial mistake.

I fixed it for myself, and maybe one day someone will fix this very old problem.

0
source

Maybe overriding modules can help you. The default level can be configured using the module AppLevel:

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 override module:

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

, AppModule 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

. , Level :

class Some
{
  @Injected(optional = true)
  private Level level = Level.NORMAL;
}

Some. - Guice - , .

+5

The solution, but unfortunately not using annotations, would be:

enum Level 
{
    NORMAL, FANCY, DEBUGGING;

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

then define the module as follows:

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

Source: https://habr.com/ru/post/1795794/


All Articles