Link to a CDI Bean in an Unmanaged CDI Bean

Is it possible to get a CDI bean instance inside a class created using the new keyword? Currently, we are making some improvements for the old application, and we always get a ContextNotActiveException every time we do a programmatic search on the CDI Singleton beans in our application.

Code to get the link:

 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; } } 
+2
java java-ee-6 cdi openwebbeans
source share
1 answer

There are 2 possible solutions.

  • If you have a JavaEE-7 container, you can use CDI.current().get(MySingletonClass.class);

  • If you have a JavaEE-6 container or even a Java SE application, you can use the Apache DeltaSpike BeanProvider . It tries to find the BeanManager from JNDI, but also performs other tricks that also work if you don't have a full EE container. For example. in SE and unit test.

You also need to make sure that not only the container is loaded, but also that the contexts are actually activated. This is usually done using the ServletListener. If you are in an EE container, they register it for you. If you use a simple tomcat, pier, etc., then you need to activate it yourself.

See this example from Apache OpenWebBeans.

+1
source share

All Articles