Chapter 6. Contexts and Dependency Injection

Contexts and Dependency Injection (CDI) is defined as JSR 299, and the complete specification can be downloaded from

CDI defines a type-safe dependency injection mechanism in the Java EE platform. A bean specifies only the type and semantics of other beans it depends upon, without a string name and using the type information available in the Java object model. This allows compile-time validation in addition to deployment. It also provides for easy refactoring.

The injection request need not be aware of the actual lifecycle, concrete implementation, threading model, or other clients of the bean. This “strong typing, loose coupling” makes your code easier to maintain. The bean so injected has a well-defined lifecycle and is bound to lifecycle contexts. The injected bean is also called a contextual instance because it is always injected in a context.

Almost any POJO can be injected as a CDI bean. This includes EJBs, JNDI resources, entity classes, and persistence units and contexts. Even the objects that were earlier created by a factory method can now be easily injected. Specifically, CDI allows EJB components to be used as JSF managed beans, thus bridging the gap between the transactional and the web tier. It is also integrated with Unified Expression Language (UEL), allowing any contextual object to be used directly within a JSF or JSP page.

Injection Points

A bean may be injected ...

Get Java EE 6 Pocket Guide now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.