【发布时间】:2011-07-18 17:15:18
【问题描述】:
有没有办法获取所有 @ApplicationScoped 的 Seam 3 组件类?
【问题讨论】:
有没有办法获取所有 @ApplicationScoped 的 Seam 3 组件类?
【问题讨论】:
自己没试过,只是看了16.5. The Bean interfaceWeld之章documentation后猜测
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;
}
}
更新
要获得Bean 的instance:
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;
}
【讨论】:
如果你想从 applicationContext 中的组件调用方法或使用 this 中的字段,最好将其定义为生产者方法或字段并将其注入到你想要的地方。
【讨论】:
您将使用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.
}
【讨论】: