是否可以在使用new
关键字创建的类中获取 CDI bean 的实例?我们目前正在对旧应用程序进行一些增强,并且每次在我们的应用程序中对 CDI Singleton bean 进行编程查找时,我们总是会收到 ContextNotActiveException 。
获取参考的代码:
public class ClassCreatedWithNew{
public void doSomething(){
MySingletonBean myBean = BeanManagerSupport.getInstance().getBean(MySingletonBean.class);
}
}
BeanManagerSupport.java
public class BeanManagerSupport {
private static final Logger LOG = Logger.getLogger(BeanManagerSupport.class);
private static final BeanManagerSupport beanManagerSupport = new BeanManagerSupport();
private BeanManager beanManager;
private BeanManagerSupport() {
try {
beanManager = InitialContext.doLookup("java:comp/BeanManager");
} catch (NamingException e) {
LOG.error("An error has occured while obtaining an instance of BeanManager", e);
}
}
@SuppressWarnings("unchecked")
public <T> T getBean(Class<T> clazz) {
Iterator<Bean< ? >> iter = beanManager.getBeans(clazz).iterator();
if (!iter.hasNext()) {
throw new IllegalStateException("CDI BeanManager cannot find an instance of requested type " + clazz.getName());
}
Bean<T> bean = (Bean<T>) iter.next();
return (T) beanManager.getContext(bean.getScope()).get(bean);
}
public static BeanManagerSupport getInstance(){
return beanManagerSupport;
}
}