Usually, when you develop a Java EE application you don’t have to bother "entering" in CDI bean graph. It’s automatically done from the UI (via expression language), CDI event triggered automatically at boot time or EJB call.

But sometimes, you may need to access CDI from non CDI code or plug non CDI code to CDI beans at run time. This part of the SPI gives you the tools to do it.

BeanManager and CDI

In CDI 1.0 the only solution you had to access CDI bean graph was to retrieve the BeanManager from JNDI

BeanManager bm = null; try { InitialContext context = new InitialContext(); bm = (BeanManager) context.lookup("java:comp/BeanManager"); } catch (Exception e) { e.printStackTrace(); }

The BeanManager is a central interface in CDI SPI, giving access to all meta-data and instantiated components in your application.

Checking its section in spec or its javadoc gives a complete overview of all the features it contains.

The main reason for developers to access CDI from non CDI code is to request a Bean instance to enter the CDI bean graph. Doing so with the BeanManager is a bit verbose.

BeanManager bm = null; try { InitialContext context = new InitialContext(); bm = (BeanManager) context.lookup("java:comp/BeanManager"); (1) } catch (Exception e) { e.printStackTrace(); } Set<Bean<?>> beans = bm.getBeans(MyService.class); (2) Bean<?> bean = bm.resolve(beans); (3) CreationalContext<MyService> ctx = bm.createCreationalContext(bean); (4) MyService myService = (MyService) bm.getReference(bean, MyService.class, ctx); (5)

1 Retrieving BeanManager thru JNDI 2 retrieving all the beans having MyService in their type and the @Default qualifier 3 apply the ambiguous dependency resolution for the set of beans 4 create a CreationalContext to help contextual instance creation for complex use cases like circularities 5 get the instance

This verbosity is the proof that the BeanManager is and advanced CDI tool allowing very basic operation on CDI echos system. It’s obviously not the best solution if you just want to access an instance.

That’s why, in CDI 1.1 we introduced the abstract CDI class which use Java Service Loader to retrieve a concrete CDI class from the implementation.

CDI<Object> cdi = CDI.current();

CDI gives a faster access to the BeanManager with CDI.getBeanManager() method, but more interestingly, it provides a convenient way to request a contextual instance without using the cumbersome code with BeanManager .

As CDI extends Instance<Object> it naturally provides contextual instance resolution with programmatic lookup.

To make short accessing CDI in your non CDI code provides the same service than having the following injection in CDI code.

@Inject @Any Instance<Object> cdi;

Retrieving an instance becomes as simple as