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?
PS: I already found org.omnifaces.cdi.BeanStorage
, but I don't have any idea how to access its map.
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.