获取运行时所有已初始化的@ Named-beans的列表 [英] Get list all initialized @Named-beans on runtime

查看:75
本文介绍了获取运行时所有已初始化的@ Named-beans的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用javax.inject.Namedjavax.enterprise.context.*Scopedorg.omnifaces.cdi.ViewScoped来定义视图bean的寿命范围.

I use javax.inject.Named and javax.enterprise.context.*Scoped plus org.omnifaces.cdi.ViewScoped to define the life-scope of my view-beans.

现在,我想获取所有实例化bean的列表.首先,我认为此博客条目涵盖了此问题,但仅列出了@ManagedBeans.

Now I want to get a list of all instantiated beans. First, I thought this blog-entry covers this issue, but it only lists @ManagedBeans.

您知道如何列出它们吗?不必将其固定在JavaEE的实现或版本上,是否可以实现?

Do you know how to list them? Is this possible without being fixed on an implementation or even a version of JavaEE?

亲切的问候, 六甲

PS:我已经找到了org.omnifaces.cdi.BeanStorage,但是我不知道如何访问其地图.

PS: I already found org.omnifaces.cdi.BeanStorage, but I don't have any idea how to access its map.

推荐答案

鉴于您正在使用OmniFaces,可以使用

Given that you're using OmniFaces, you can use Beans#getActiveInstances() method of the Beans utility class to get all active instances in a given CDI scope.

Map<Object, String> activeViewScopedBeans = Beans.getActiveInstances(ViewScoped.class);
// ...

键是bean实例,值是bean名称.

The key is the bean instance and the value is the bean name.

对于技术上感兴趣的人,这里是此实用程序方法的具体实现:

For the technically interested, here's the concrete implementation of this utility method:

public static <S extends Annotation> Map<Object, String> getActiveInstances(BeanManager beanManager, Class<S> scope) {
    Map<Object, String> activeInstances = new HashMap<>();
    Set<Bean<?>> beans = beanManager.getBeans(Object.class);
    Context context = beanManager.getContext(scope);

    for (Bean<?> bean : beans) {
        Object instance = context.get(bean);

        if (instance != null) {
            activeInstances.put(instance, bean.getName());
        }
    }

    return Collections.unmodifiableMap(activeInstances);
}

BeanStorage仅用于内部使用.此外,它没有在展示柜中列出.

The BeanStorage is for internal usage only. Moreover, it's not listed in the showcase.

这篇关于获取运行时所有已初始化的@ Named-beans的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆