X

BeanManager: Obtain Contextual Reference to Beans (TOTD #215)

Guest Author


javax.enterprise.inject.spi.BeanManager allows to
programmatically obtain contextual references to beans. Even though
the primary purpose is to allow a portable extension to interact
directly with the container, it can be used by any Java EE component
as well.



There are three ways to obtain BeanManager:
  • @Inject BeanManager bm;
  • BeanManager bm = CDI.current().getBeanManager();
  • BeanManager bm = null;

    try {

        InitialContext context = new
    InitialContext();


        bm =
    (BeanManager)context.lookup("java:comp/BeanManager");


    } catch (NamingException | NullPointerException ex)
    {


       
    Logger.getLogger(TestServlet.class.getName()).log(Level.SEVERE,
    null, ex);


        ex.printStackTrace(out);

    }

The instance is with the scope @Dependent and
qualifier @Default. It can be used to
programmatically obtain the list of beans that are available for
injection such as:



Set<Bean<?>> beans =
bm.getBeans(Greeting.class);

BeanManager has lots of other useful methods to, for example to
obtain a contextual reference, an injectable reference, and
non-contextual instance. Go read the href="http://docs.oracle.com/javaee/7/api/javax/enterprise/inject/spi/BeanManager.html">javadocs.

Check out the complete sample source code at:

href="https://github.com/arun-gupta/javaee7-samples/tree/master/cdi/beanmanager">https://github.com/arun-gupta/javaee7-samples/tree/master/cdi/beanmanager

How would you use BeanManager in your applications ?


Join the discussion

Comments ( 1 )
  • Binh Thanh Nguyen Thursday, July 25, 2013

    It's nice, simple and easy.


Please enter your name.Please provide a valid email address.Please enter a comment.CAPTCHA challenge response provided was incorrect. Please try again.