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):
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="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd"> </beans>
Define a resource
@ApplicationScoped // resource is created only once for the whole application (Singleton) public class Resource { ... }
Use resource
public class ResourceUser { @Inject Resource injectedResource; }
The main scopes in JBoss are: RequestScoped, ConversationScoped, SessionScoped, ApplicationScoped
For a web application that uses CDI
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.
see http://openejb.apache.org/examples-trunk/cdi-request-scope/
An object which is defined as @ApplicationScoped is created once for the duration of the application.
see http://openejb.apache.org/examples-trunk/cdi-application-scope/README.html
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:
However, unlike the session scope, the conversation 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