My goal is to collect a collection of all managed CDI beans (of a specific parent class) from JSF2 ExceptionHandlerWrapper. Note that the part of the exception handler is significant because the class is not the actual target of the injection. So my assumption (possibly wrong) is that my only route is software using BeanManager.
Using BeanManager.getBeans, I can successfully get the set of all beans available for injection. My problem is that when using BeanManager.getReference to get a context instance of a bean, a bean will be created if it does not already exist. Therefore, I am looking for an alternative that will only return an instance of beans. The code below is my starting point
public List<Object> getAllWeldBeans() throws NamingException { //Get the Weld BeanManager InitialContext initialContext = new InitialContext(); BeanManager bm = (BeanManager) initialContext.lookup("java:comp/BeanManager"); //List all CDI Managed Beans and their EL-accessible name Set<Bean<?>> beans = bm.getBeans(AbstractBean.class, new AnnotationLiteral<Any>() {}); List<Object> beanInstances = new ArrayList<Object>(); for (Bean bean : beans) { CreationalContext cc = bm.createCreationalContext(bean); //Instantiates bean if not already in-service (undesirable) Object beanInstance = bm.getReference(bean, bean.getBeanClass(), cc); beanInstances.add(beanInstance); } return beanInstances; }
source share