简体   繁体   English

如何为Guice指定默认的Enum实例?

[英]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 这将使Guice为表达式返回Level.NORMAL

injector.getInstance(Level.class)

There's no such thing like @DefaultInstance . 没有@DefaultInstance这样的东西。 As a workaround I've tried @ProvidedBy with a trivial Provider , but it doesn't work. 作为一种解决方法,我尝试了@ProvidedBy与一个简单的Provider ,但它不起作用。

Maybe overriding modules could help you. 也许重写模块可以帮助你。 A default level can be configured using AppLevel 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 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: 最后,只需使用特定的Level配置创建一个覆盖AppModule的注入器:

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 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: 假设Level在类中用作注入字段:

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 . 默认级别将初始化为创建Some实例的Some If some Guice config module declares some other level it will be optionally injected. 如果一些Guice配置模块声明了某个其他级别,它将被选择性地注入。

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. 这是问题295 ,看起来像一个非常微不足道的bug。

I've patched it for myself and maybe one day somebody there will fix this very old issue, too. 我已经为自己打补丁了,也许有一天,有人会解决这个非常古老的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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