Contexts and Dependency Injection (CDI) integration with EJB container
The CDI specification enhances the EJB component model with contextual life cycle management.
Relationship of the CDI to the EJB specification
The EJB specification defines a programming model for application components that access transactional resources in a multi-user environment. Concerns, such as role-based security, transaction demarcation, concurrency, and scalability are specified declaratively by using annotations and XML deployment descriptors that are enforced by the EJB container at run time. EJB components might be stateful, but are not contextual by nature.
- Contextual
- Bound to a lifecycle context
- Available to other instances that launch in that context
- Container creates an instance when needed
- Container deletes an instance when context ends
The WebSphere® Application Server tradicional CDI container performs dependency injection on all session and message-driven bean instances, even instances that are not contextual instances. WebSphere Application Server CDI supports injection of CDI beans inside enterprise beans and vice versa.
Usage

- Use the @Inject method for contextual injection of local session beans.
- Use the @EJB method for remote session beans
Define producers that are making the EJB available for non-contextual injection:
@Produces @EJB PaymentService paymentService;
@Inject PaymentService myPaymentService
Practical considerations
You can define CDI-style interceptors with interceptor bindings and decorators enterprise beans. Interceptors are declared by using @Interceptors methods or in ejb-jar.xml files, which are called before interceptors and are declared by using interceptor bindings. Interceptors are called before decorators.When a contextual @Injected instance of an EJB container is destroyed as a result of going out of scope, and if the underlying EJB container was not already removed by direct invocation of a remove method by the application, the WebSphere Application Server tradicional CDI container removes the stateful session bean.
- When you use the @Inject method to create a contextual injection instance and that instance in an EJB container is destroyed as a result of going out of scope.
- When the underlying EJB container was not already removed by direct invocation of a remove method by the application.
You must also consider the scope and state propagation of CDI beans. The request and application scope CDI beans maintain state in their respective contexts across the web and EJB containers. For instance, a request-scoped CDI bean injected in a servlet holds its state when a business method on stateful session enterprise bean accesses the same request-scoped bean.