2013-03-25 65 views
0

我有一個名爲CDI @Named的bean。例如,'firedEmployeeBean'。CDI。如何檢查bean是否實例化?

其他CDI bean有沒有辦法檢查'firedEmployeeBean'是否已經實例化?

+6

它更像是量子物理學 - 一旦你檢查它:) – kostja 2013-03-25 14:55:18

+0

這一切都取決於你的注射器將被實例化。 – 2013-03-25 14:58:28

回答

3

如前所述,如果您使用@Inject一旦您檢查它會。什麼,你不是想要的是有一個屬性來告訴你想要的東西:

boolean initiated; 

如果這個簡單的解決方案不剪,我會建議使用Deltaspike:

MyBean myBean = BeanProvider.getContextualReference(MyBean.class, true); 

注意第二個參數, true - 來自文檔:如果您查找給定接口的實現並且不需要實現,或者不需要具有給定限定符的實例,則傳遞true作爲第二個參數(請參閱限定符示例更多細節)。http://incubator.apache.org/deltaspike/core.html

最後您可以使用事件。在CDI中使用事件非常簡單。你需要做的是在bean創建時觸發事件並讓其他bean觀察該事件。 http://docs.jboss.org/weld/reference/latest/en-US/html/events.html

+2

注意:如果你想對'firedEmployeeBean'初始化做出反應,你可以添加一個'@ PostConstruct'註解的方法。在'firedEmployeeBean'中執行完所有注入之後,將調用此方法。 – omilke 2013-03-26 09:31:31

1

作爲一種替代方案,您可以使用CDI BeanManager手動在給定的上下文(或根本沒有上下文)內拉出一個bean。例如,以JSF上下文爲例,可以使用以下代碼片段在上下文中提取MyBean的所有活動實例。

public void findBean(String beanName, FacesContext facesContext){ 
     BeanManager cdiBeanManager = (BeanManager)((ServletContext) facesContext.getExternalContext().getContext()).getAttribute("javax.enterprise.inject.spi.BeanManager"); //get the BeanManager in your operational context 
     Bean bean = cdiBeanManager.getBeans(beanName).iterator().next(); //this actually returns a Set, but you're only interested in one 
     CreationalContext ctx = cdiBeanManager.createCreationalContext(bean); 
     MyBean theActualBean = cdiBeanManager.getReference(bean, bean.getClass(),ctx); //retrieve the bean from the manager by name. You're guaranteed to retrieve only one of the same name within the given context; 

    } 

這是一個純Java EE實現,沒有第三方庫

相關問題