我的目标是从JSF2 ExceptionHandlerWrapper中获取所有服务中CDI托管bean(某个父类)的集合。请注意,异常处理程序部分很重要,因为该类本身不是有效的注入目标。所以我的假设(可能不正确)是我唯一的路由是通过BeanManager编程的。
使用BeanManager.getBeans,我可以成功获取可用于注入的所有bean的集合。我的问题是,当使用BeanManager.getReference来获取bean的上下文实例时,如果bean尚不存在,则将创建该bean。所以我正在寻找一种只返回实例化bean的替代品。下面的代码是我的出发点
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;
}
答案 0 :(得分:7)
我们在这里......通过javadoc找到Context,它有两个版本的bean实例的get()方法。其中一个在传递创建上下文时具有与BeanManager.getReference()相同的行为。然而,另一个只接受Bean引用并返回上下文实例(如果可用)或null。
利用它,这是原始方法的版本,它只返回实例化的bean:
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;
}