Get list all initialized @Named-beans on runtime

烂漫一生 提交于 2019-12-07 09:05:48

问题


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

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.

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

Kind regards, Rokko

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


回答1:


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);
// ...

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);
}

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



来源:https://stackoverflow.com/questions/33478927/get-list-all-initialized-named-beans-on-runtime

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