Contexts and Dependency Injection (CDI): Java Platform, Enterprise Edition (Java EE) 5 brought dependency injection (DI) with Convention over Configuration to Enterprise JavaBeans (EJB) 3.0. Java EE 6 introduces the flexible and powerful @Inject dependency injection model (JSR-330 and JSR-299) in addition to the already existing @EJB annotation.
Contexts and Dependency Injection (CDI) is a new Java EE 6 specification, which not only defines a powerful and type-safe Dependency Injection, but also introduces the concept of "contextual" references or scopes.
The "C" in CDI is the main difference between EJB beans and managed CDI beans. CDI-managed beans are contextual and EJB beans are not. Managed beans in CDI live in well-defined scope. They are created and destroyed on demand by the container. CDI comes already with pre-defined scopes and annotations :
@RequestScoped
@SessionScoped
@ApplicationScoped
@ConversationScoped
.
The CDI container manages all beans inside the scope automatically for you. At the end of an HttpSession
or HttpRequest, all instances associated with this scope are automatically destroyed and, thus, garbage collected.
This behavior is very different from that of Stateful session beans. A Stateful session bean instance needs to be explicitly removed by the client with the invocation of a method annotated with @Remove
. It will not be automatically destroyed by the container; it is not bound to any context. If you associate a Stateful session bean with the HttpSession
, you also have to care about its reliable destruction at the end or timeout of the HttpSession
.
The contextual nature of CDI makes the use of beans from different scopes more natural and convenient. You can even mix and match scopes and inject beans from different scopes. The container will still care about proper lifecycle management.