Search code examples
javajakarta-eejsf-2

Get List of All Managed Beans in JSF at runtime


I'd like to get a list of all managed beans in a JSF application. In Spring, I can do something like context.getBeansOfType(). Is there a corresponding method in JSF?

I have a number of @ManagedProperty beans that implement an interface. I'd like to get a list of these adapters and loop through them rather than invoke each bean explicitly in order to keep the code clean.

Thank you


Solution

  • You can do this with BeanManager class from com.sun.faces.mgbean package:

    ApplicationAssociate application = ApplicationAssociate.getInstance(FacesContext.getCurrentInstance().getExternalContext());
    BeanManager beanManager = application.getBeanManager();
    Map<String, BeanBuilder> beanMap = beanManager.getRegisteredBeans();
    Set<Entry<String, BeanBuilder>>beanEntries = beanMap.entrySet();
    
    for (Entry<String, BeanBuilder> bean: beanEntries) {
      String beanName = bean.getKey();
      if (beanManager.isManaged(beanName)) {
        BeanBuilder builder = bean.getValue();
        System.out.println("Bean name: " + beanName);
        System.out.println("Bean class: " + builder.getBeanClass());
        System.out.println("Bean scope: " + builder.getScope());
      }
    }
    

    NOTE: This is tightly coupled with Mojarra JSF implementation and doesn't work on other implementations.