Get List of All Managed Beans in JSF at runtime

拜拜、爱过 提交于 2019-12-24 01:23:54

问题


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


回答1:


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.




回答2:


If your beans are already in the session you can try the code below:

Map<String, Object> sessionMap = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
for (Entry<String, Object> beanEntry : sessionMap.entrySet()) {
    String beanName = beanEntry.getKey();
    Object bean = beanEntry.getValue();
    //TODO do something with bean, i.e. check if it's implements your interface and store into list
}

By saying that a bean is in the session I mean that the bean is already created and used in another object in the same session.



来源:https://stackoverflow.com/questions/15502280/get-list-of-all-managed-beans-in-jsf-at-runtime

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!