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


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 javadocs.

Check out the complete sample source code at:

https://github.com/arun-gupta/javaee7-samples/tree/master/cdi/beanmanager

How would you use BeanManager in your applications ?

Comments:

It's nice, simple and easy.

Posted by Binh Thanh Nguyen on July 24, 2013 at 08:59 PM PDT #

Post a Comment:
Comments are closed for this entry.
About

profile image
Arun Gupta is a technology enthusiast, a passionate runner, author, and a community guy who works for Oracle Corp.


Java EE 7 Samples

Stay Connected

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today