2016-03-07 61 views
1

我在使用EJB注入中的一種策略時遇到了CDI條件 注入的問題。使用基於@Inject字段的@Qualifier CDI

我的實際場景是

public class someManagedBean { 

    @Inject 
    @MyOwnQualifier(condition = someBean.getSomeCondition()) // not work because someBean is not already injected at this point 
    private BeanInterface myEJB; 

    @Inject 
    SomeBean someBean; 
} 

@Qualifier 
@Retention(RetentionPolicy.RUNTIME) 
@Target({ElementType.FIELD, ElementType.METHOD}) 
public @interface MyOwnQualifier { 
    SomeCondition condition(); 
} 

public class BeanInterfaceFactory { 
    @Produces 
    @MyOwnQualifier(condition = RoleCondition.ADMIN) 
    public BeanInterface getBeanInterfaceEJBImpl() { 
     return new BeanInterfaceEJBImpl(); 
    } 
} 

public enum RoleCondition { 
    ADMIN("ADMIN User"); 
} 

好,場景解釋。現在問題是我需要從someBean.getSomeCondition()獲得值 ,該值返回RoleCondition,這對我的@MyOwnQualifier是必需的。 但是此時someBean還沒有被CDI注入。

我如何使這條線路工作?

@Inject 
@MyOwnQualifier(condition = someBean.getSomeCondition()) // not work because some is not already injected at this point 
private BeanInterface myEJB; 

如何動態地注入使用基於另一種注射的屬性值預選賽豆的正確方法?

+1

我實在不明白這是如何工作過,因爲註釋是編譯時的事情,someBean.getSomeCondition()計算在運行時。我更想你想創建一個可以有條件地提供實例的生產者。 https://docs.jboss.org/weld/reference/1.0.0/en-US/html/producermethods.html – Gimby

+0

在嘗試注入之前,沒有像'beforeConstruct'這樣的事情來評估一些值嗎? –

回答

4

嘗試......

public class someManagedBean { 

    @Inject 
    @MyOwnQualifier 
    private BeanInterface myEJB; 
} 

@Qualifier 
@Retention(RetentionPolicy.RUNTIME) 
@Target({ElementType.FIELD, ElementType.METHOD}) 
public @interface MyOwnQualifier { 
    SomeCondition condition(); 
} 

public class BeanInterfaceFactory { 

    @Inject 
    SomeBean someBean 

    @Produces 
    @MyOwnQualifier 
    public BeanInterface getBeanInterfaceEJBImpl() { 
     if(someBean.getCondition()) {   
      return new BeanInterfaceEJBImpl(); 
     } else { 
      .... 
     } 
    } 
} 

public enum RoleCondition { 
    ADMIN("ADMIN User"); 
} 
+0

首先,感謝您的幫助。 someBean出於某種原因在此時出廠時爲null'getBeanInterfaceEJBImpl' –

+0

if null表示BeanInterfaceFactory不是一個cdi bean,請嘗試添加@Named。在beans.xml中使用哪種發現模式? – fantarama

+0

是的,對不起我的無知哈哈,午餐後我會檢查一切是否正常,顯然它會奏效。非常感謝你,你是最棒的:) –