获取仅在服务中的CDI管理的bean

6
我的目标是从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;
}
1个回答

7

在这里......浏览javadoc时,我找到了 Context ,其中有两个版本的get()方法用于Bean实例。 其中一个,在传递创建上下文时,与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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接