问题
I've got a name of CDI @Named bean. For example, 'firedEmployeeBean'.
Is there any way in other CDI bean check whether 'firedEmployeeBean' already instantiated or not?
回答1:
As already stated if you use @Inject
once you check it will be. What you instead want is to have a property to tell you what you want:
boolean initiated;
if this simple solution does not cut it I would recommend to use Deltaspike:
MyBean myBean = BeanProvider.getContextualReference(MyBean.class, true);
Note the second argument, true - from docs: Pass true as second argument, if you look for an implementation of the given interface and an implementation isn't required or it isn't required that there is an instance with the given qualifier (see the qualifier example for further details). http://incubator.apache.org/deltaspike/core.html
Lastly you can use events. Events are really simple to use in CDI. What you need to do is fire the event when the bean is created and have the other bean observe that event. http://docs.jboss.org/weld/reference/latest/en-US/html/events.html
回答2:
As an alternative, you can use the CDI BeanManager to manually pull up a bean within a given context (or no context at all). Take a JSF context for example, you can use the following snippet to pull all active instances of MyBean
within the context.
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;
}
This is a pure Java EE implementation, no third party libs
来源:https://stackoverflow.com/questions/15617912/cdi-how-to-check-whether-bean-instantiated-or-not