如何在当前视图(范围)中找到/的CDI bean? [英] How do you find CDI beans of/in the current view (scope)?
问题描述
在 Java EE 6,CDI 1.1.x,Seam 3等环境中,我们需要查找当前视图的所有CDI bean( @ViewScoped
)。我到目前为止尝试使用的是:
In a Java EE 6, CDI 1.1.x, Seam 3 etc. environment, we need to find all CDI beans of the current view (@ViewScoped
). What I have tried so far is using:
@Named
@ViewScoped
public class ViewHelper
{
@Inject
private BeanManager beanManager;
public doSomethingWithTheBeanInstances()
{
Set<Bean<?>> beans = this.getBeanManager().getBeans(
Object.class, new AnnotationLiteral<Any>(){}
);
// do something
...
}
}
然而,这会返回它管理的所有 bean。
However, this returns all beans it manages.
我只需找到那些中的当前视图的范围和 - 这将是理想的 - 只有那些实现特定接口(通过多个层次结构级别继承)。
I need to find only those within the scope of the current view and - that would be ideal - only those that implement a specific interface (inherited over over multiple hierarchy levels).
这是什么方式要做吗?
注意,由于CDI没有视图范围,我们使用 Seam 3 来注释我们所有的视图范围bean如:
Note since CDI has no view scope, we're using Seam 3 to be able to annotate all our view-scoped beans like:
@Named
@ViewScoped
public class ResultManagerColumnHandler extends BaseColumnHandler
{
....
}
以上是寻找的实例( @ViewScoped
是Seam 3的CDI替代品。)
The above would be an instance to look for (the @ViewScoped
is a CDI replacement by Seam 3).
怎么办?
推荐答案
我不熟悉Seam,但来自CDI标准t,这就是我想要的。但是,请注意,如果 beanManager.getContext(ViewScoped.class);
为您返回一个有效的上下文实例>> :
I am not familiar with Seam, but from CDI standpoint, this is what I would try. However, bean it mind that it will only work if beanManager.getContext(ViewScoped.class);
returns a valid context instance for you:
@Inject
BeanManager bm;
public List<Object> getAllViewScoped() {
List<Object> allBeans = new ArrayList<Object>();
Set<Bean<?>> beans = bm.getBeans(Object.class);
// NOTE - context has to be active when you try this
Context context = bm.getContext(ViewScoped.class);
for (Bean<?> bean : beans) {
Object instance = context.get(bean);
if (instance != null) {
allBeans.add(instance);
}
}
return allBeans;
}
您还要求只获取实现特定接口的bean。为此,只需修改代码行,检索所需类型的所有bean:
You also asked to only obtain beans that implement certain interface. For that, simply modify the code line retrieving all beans with desired type:
Set<Bean<?>> beans = bm.getBeans(MyInterface.class);
这篇关于如何在当前视图(范围)中找到/的CDI bean?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!