CDI。 如何检查bean是否实例化?

我有一个CDI @Named bean的名字。 例如,’firedEmployeeBean’。

在其他CDI bean中是否有任何方法检查’firedEmployeeBean’是否已经实例化?

如前所述,如果你使用@Inject ,你会检查它。 你想要的是拥有一个属性来告诉你你想要什么:

 boolean initiated; 

如果这个简单的解决方案没有削减它我会建议使用Deltaspike:

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

注意第二个参数,true – 来自docs: 如果查找给定接口的实现并且不需要实现,或者不要求存在具有给定限定符的实例,则将true作为第二个参数传递(请参阅进一步细节的限定符示例)。 http://incubator.apache.org/deltaspike/core.html

最后,您可以使用事件。 事件在CDI中使用起来非常简单。 您需要做的是在创建bean时激活事件并让另一个bean观察该事件。 http://docs.jboss.org/weld/reference/latest/en-US/html/events.html

作为替代方案,您可以使用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实现,没有第三方库