Wednesday Jul 24, 2013

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 ?

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
« July 2013 »
SunMonTueWedThuFriSat
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
19
20
22
25
26
27
28
29
30
31
   
       
Today