1

有没有办法获得所有 @ApplicationScoped 的 Seam 3 组件类?

4

3 回答 3

2

自己没试过,只是在阅读Weld文档16.5. The Bean interface章节后的猜测

class ApplicationScopedBeans {
    @Inject BeanManager beanManager;

    public Set<Bean<?>> getApplicationScopedBeans() {
        Set<Bean<?>> allBeans = beanManager.getBeans(Object.class, new AnnotationLiteral<Any>() {});
        Set<Bean<?>> result = new HashSet<Bean<?>>();
        for(Bean<?> bean : allBeans) {
            if(bean.getScope().equals(ApplicationScoped.class)) {
                result.add(bean);
            }
        }
        return result;
    }
}

更新

要获得instancea Bean

public Object getApplicationScopedInstance(Bean<?> bean) {
    CreationalContext ctx = beanManager.createCreationalContext(bean);
    Context appCtx = beanManager.getContext(ApplicationScoped.class);
    return appCtx.get(bean, ctx);
}

更新 2

看起来以上所有内容都错过了 CDI 的全部要点 :)

class ApplicationScopedBeans {
    @Inject @ApplicationScoped Instance<Object> appScopedBeans;

}
于 2011-07-10T19:16:53.637 回答
1

如果您想从 applicationContext 中的组件调用方法或使用其中的字段,最好将其定义为生产者方法或字段并将其注入您想要的位置。

于 2011-07-10T09:38:56.800 回答
0

您将用于 getApplicationContext()获取上下文,然后getNames()用于获取应用程序范围内事物的所有名称,然后您将用于get()按名称检索它们。

你想做什么?从那里你必须使用反射来让它们成为正确的类型..

Context appContext = Contexts.getApplicationContext();
String [] names = appContext.getNames();
//Do whatever with them..
for(String s : names){
   Object x = appContext.get(name);
   // do something.
}
于 2011-03-19T12:06:42.293 回答