有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何为Guice指定默认枚举实例?

我需要像这样的东西

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

这将使Guice为表达式返回Level.NORMAL

injector.getInstance(Level.class)

没有像@DefaultInstance这样的东西。作为一种解决方法,我尝试了一个简单的Provider,但它不起作用


共 (3) 个答案

  1. # 1 楼答案

    一个解决方案(但不幸的是不使用注释)是:

    enum Level 
    {
        NORMAL, FANCY, DEBUGGING;
    
        static final Level defaultLevel = FANCY; //put your default here
    }
    

    然后定义如下模块:

    public class DefaultLevelModule extends AbstractModule 
    {
        @Override public void configure() 
        {
            bind(Level.class).toInstance(Level.defaultLevel);
        }
    }
    
  2. # 2 楼答案

    它是the issue 295,看起来像一个非常小的bug

    我已经为自己修补好了,也许有一天那里的某个人也会修复这个非常老的问题

  3. # 3 楼答案

    也许重写模块可以帮助您。可以使用AppLevel模块配置默认级别:

    public class AppModule extends AbstractModule {
        @Override
        public void configure() {
            bind(Level.class).toInstance(Level.NORMAL);
            // other bindings
        }
    }
    

    可以在一个小型覆盖模块中配置一个特定的覆盖模块:

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

    最后,只需创建一个注入器,用特定的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));
    }
    

    更新

    这个问题可以用另一种方式解决。假设Level在类中用作注入字段:

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

    默认级别将作为Some实例创建的一部分进行初始化。如果某个Guice配置模块声明了另一个级别,那么它将被选择性地注入