User Tools

Site Tools



CDI is the Java standard for dependency injection (DI) and interception (AOP). Dependency Injection refers to the process of supplying an external dependency to a software component. DI can help make your code architecturally pure. It aids in design by interface as well as test-driven development by providing a consistent way to inject dependencies.

For example, a data access object (DAO) may depend on a database connection. Instead of looking up the database connection with JNDI, you could inject it.

JBoss uses Weld which is the reference implementation for CDI(JSR-299):

JBoss Prerequisites

There's just little one thing you need to do to enable CDI in your JBoss project: make sure your archive (.war, .ear, ..) contains a special marker file: WEB-INF/beans.xml (or META-INF/beans.xml )

<beans xmlns=""

Simple Example

Define a resource

@ApplicationScoped // resource is created only once for the whole application (Singleton)
public class Resource { ... }

Use resource

public class ResourceUser {
   Resource injectedResource; 


The main scopes in JBoss are: RequestScoped, ConversationScoped, SessionScoped, ApplicationScoped

For a web application that uses CDI

  • any servlet request has access to active request, session and application scopes
  • any JSF request has access to an active conversation scope


This is the default scope if none is specified; it means that an object exists to serve exactly one client (bean) and has the same lifecycle as that client.


An object which is defined as @RequestScoped is created once for every request and is shared by all the beans that inject it throughout a request.




An object which is defined as @ApplicationScoped is created once for the duration of the application.



A conversation represents a task—a unit of work from the point of view of the user. The conversation context holds state associated with what the user is currently working on. If the user is doing multiple things at the same time, there are multiple conversations.

The conversationScope is similar to the traditional session scope:

  • it holds state associated with a user of the system
  • it spans multiple requests to the server

However, unlike the session scope, the conversation scope:

  • is demarcated explicitly by the application
  • holds state associated with a particular web browser tab in a JSF application (browsers tend to share domain cookies, and hence the session cookie, between tabs, so this is not the case for the session scope

The conversation context is active during any JSF request. Most conversations are destroyed at the end of the request. If a conversation should hold state across multiple requests, it must be explicitly promoted to a long-running conversation

External Resources

java_cdi.txt · Last modified: 2014/01/20 09:58 by hkoller