【问题标题】:Injecting arbitrary enum with WELD CDI使用 WELD CDI 注入任意枚举
【发布时间】:2015-08-06 20:21:46
【问题描述】:

我试图提供一个机会,可以在给定的注入点和字符串值(在 Produces 方法中获得)注入任意枚举

任意意味着如果我有 enum My 和 enum Your 我想用相同的生产者方法注入它们或任何其他。

所以我尝试了几种方法: 1.

@Produces
@MyConfigAnnotation
Enum getArbitraryEnum(InjectionPoint point) {
    ...
    // get string representation, 
    // instantiate enum using point
    return Enum.valueOf((Class<Enum>)injectionPoint.getAnnotated().getClass(), enumValue);
}

2。我将返回类型更改为 Object。

在这两种情况下,我都会收到下一个异常 引起:org.jboss.weld.exceptions.DeploymentException:WELD-001408:在注入点 [BackedAnnotatedField] @Inject @X pathToMyField.testEnum2 带有限定符 @X 的类型 TestEnum 的依赖关系不满足

那么有没有办法创建一个能够产生任意枚举的 Produces 方法。

【问题讨论】:

  • 你能提供更多你的生产者方法吗?你在运行什么容器?
  • @JohnAment 我已经添加了我试图实例化枚举的方式。但这并不重要,因为该应用程序似乎没有进入方法。关于容器,我使用的是 Jboss Weld,还是您的意思有所不同?

标签: java dependency-injection cdi weld


【解决方案1】:

您需要有实例和限定符的唯一组合,因为没有限定符,weld 不知道要调用哪个生产者。

有一种实现动态枚举绑定的方法,我在这篇文章的cmets中找到了:http://www.ocpsoft.org/java/how-to-inject-enum-values-into-cdi-beans/

public class InjectedObject {
   private MyEnum e1;
   private MyEnum e2;
   private MyEnum e3;

   @Inject
   public InjectedObject(@Config("ONE") MyEnum e1, @Config("TWO") MyEnum e2,     @Config("THREE") MyEnum e3)   {
      this.e1 = e1;
      this.e2 = e2;
      this.e3 = e3;
   }


   /**
    * A producer is required in order to {@link Inject} an Enum
    */
   @Produces
   @Config
   public static MyEnum getEnum(InjectionPoint ip) {
       String name = null;

       /**
        * Iterate over all Qualifiers of the Injection Point to find our configuration and save the config value
        */
       for(Annotation a : ip.getQualifiers()) {
           if(a instanceof Config) {
               name = ((Config) a).value();
           }
       }

       /**
        * Iterate over all enum values to match them against our configuration value
        */
       for(MyEnum me : MyEnum.values()) {
           if(me.toString().equals(name)) {
               return me;
           }
       }

      return null;
   }

    /**
    * Our enum
    */
   public enum MyEnum {      ONE, TWO, FOO   }

   @Qualifier
   @Target({ TYPE, METHOD, PARAMETER, FIELD })
   @Retention(RUNTIME)
   @Documented
   public @interface Config {
       @Nonbinding String value() default "";
   }
}

有趣的部分当然是具有非绑定值的自定义限定符,导致 CDI 选择正确的生产者方法。

说了这么多...因为您需要一个额外的限定符,它以某种方式包含您要注入的枚举的名称...为什么要注入?

【讨论】:

  • 对不起,误导性代码,但我实际上使用限定符(编辑问题)。当然,谢谢你的回答,但问题的关键字是 arbitrary 枚举。这意味着无论注入什么枚举,它都会注入一个相同的生产者方法。但是,在您的示例中,您会生成精确的枚举类 MyEnum
猜你喜欢
  • 2011-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-27
  • 2021-02-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多