SeamFramework.orgCommunity Documentation

Chapter 8. Obtaining a handle on the BeanManager

When developing a framework that builds on CDI, you may need to obtain the BeanManager for the application, can't simply inject it as you are not working in an object managed by the container. The CDI specification allows lookup of java:comp/BeanManager in JNDI, however some environments don't support binding to this location (e.g. servlet containers such as Tomcat and Jetty) and some environments don't support JNDI (e.g. the Weld SE container). For this reason, most framework developers will prefer to avoid a direct JNDI lookup.

Often it is possible to pass the correct BeanManager to the object in which you require it, for example via a context object. For example, you might be able to place the BeanManager in the ServletContext, and retrieve it at a later date.

On some occasions however there is no suitable context to use, and in this case, you can take advantage of the abstraction over BeanManager lookup provided by Weld Extensions. To lookup up a BeanManager, you can extend the BeanManagerAware class, and call getBeanManager:

class WicketIntegration extends BeanManagerAware {


   public WicketManager getWicketManager() {
      Bean<?> bean = getBeanManager.getBean(Instance.class);
      ...   
   }
   
   ...
}

Occasionally you will be working in an existing class hierarchy, in which case you can use the static accessors on BeanManagerAccessor. For example:

class ResourceServlet extends HttpServlet {


   protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
         throws ServletException, IOException {
      BeanManager beanManager = BeanManagerAccessor.getBeanManager();
      ...
   }
}