Get only managed CDI without beans maintenance

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; } 
+6
source share
1 answer

Here we are ... wading through javadoc, I found Context , which has two versions of get () for bean instances. One of them, when passed in the context of creation, has the same behavior as BeanManager.getReference (). However, the other simply accepts the bean reference and returns either a context instance (if one is available) or null.

Using this, here is the version of the original method that returns only the beans instance:

 public List<Object> getAllCDIBeans() throws NamingException { //Get the BeanManager via JNDI InitialContext initialContext = new InitialContext(); BeanManager bm = (BeanManager) initialContext.lookup("java:comp/BeanManager"); //Get all CDI Managed Bean types Set<Bean<?>> beans = bm.getBeans(Object.class, new AnnotationLiteral<Any>() {}); List<Object> beanInstances = new ArrayList<Object>(); for (Bean bean : beans) { CreationalContext cc = bm.createCreationalContext(bean); //Get a reference to the Context for the scope of the Bean Context beanScopeContext = bm.getContext(bean.getScope()); //Get a reference to the instantiated bean, or null if none exists Object beanInstance = beanScopeContext.get(bean); if(beanInstance != null){ beanInstances.add(beanInstance); } } return beanInstances; } 
+7
source

Source: https://habr.com/ru/post/958155/


All Articles