DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

  1. DZone
  2. Refcards
  3. Contexts and Dependency Injection for the Java EE Platform
refcard cover
Refcard #083

Contexts and Dependency Injection for the Java EE Platform

Understanding CDI

Java EE 6 introduced Contexts and Dependency Injections (CDI) as a set of component management services that allow for loose coupling of components across layers (through dependency injection) in a type-safe way. The benefits of CDI include a simplified architecture and more reusable code. In this newly updated Refcard, you will learn about the main features of CDI 1.2 in Java EE 7, how to get the most from CDI, and how to get your CDI code up and running.

Download Refcard
Free PDF for Easy Reference
refcard cover

Written By

author avatar Antoine Sabot-Durand
Senior Software Engineer, Red Hat
author avatar Norman Richards
Developer, ThreatGRID, Inc.
Table of Contents
► About CDI ► Getting started with CDI ► Activating and configuring CDI ► The CDI container ► Beans and contextual instances ► Bean vs. Contextual instances ► Defining an Injection Point ► Different kinds of CDI beans ► Qualifiers ► Typesafe resolution ► Programmatic lookup ► Accessing CDI from non-CDI code ► Events ► Interceptors and Decorators ► Going further with CDI
Section 1

About CDI

Contexts and Dependency Injection for the Java EE Platform (CDI) introduces a standard set of component management services to the Java EE platform. CDI manages the lifecycle and interactions of stateful components bound to well-defined contexts. CDI provides typesafe dependency injection between components. CDI provides interceptors and decorators to extend the behavior of components, an event model for loosely coupled components, and an SPI allowing portable extensions to integrate cleanly with the Java EE environment.

CDI and Java EE

CDI is included in Java EE since Java EE 6 (CDI 1.0). The EE 6 platform was designed to make sure all EE components make use of CDI services, putting CDI directly at the heart of the platform, welding together the various EE technologies.

In Java EE 7 (and CDI 1.2) this integration goes further with the automatic enablement of CDI in the platform and more integration with other specs.

This document covers the main features of CDI 1.2, included in all Java EE 7 application servers.

CDI implementations

CDI 1.2 has 2 known implementations:

  • JBoss Weld, the reference implementation, used by JBoss EAP, WildFly, Glassfish, Oracle WebLogic, and IBM Websphere, among others
  • Apache OpenWebBeans, used by Apache TomEE server
Section 2

Getting started with CDI

The easiest way to start writing and running CDI code is to write a Java EE 7 application and deploy it on your favorite server. (WildlFly is a good choice if you don’t have any).

The simplest Maven POM to start developing a Java EE 7 application is only 21 lines long:

​x
1
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3
    <modelVersion>4.0.0</modelVersion>
4
    <groupId>com.dzone</groupId>
5
    <artifactId>javaee7-basic-pom</artifactId>
6
    <version>7.0</version>
7
    <packaging>war</packaging>
8
    <dependencies>
9
        <dependency>
10
            <groupId>javax</groupId>
11
            <artifactId>javaee-api</artifactId>
12
            <version>7.0</version>
13
            <scope>provided</scope>
14
        </dependency>
15
    </dependencies>
16
    <properties>
17
        <maven.compiler.source>1.7</maven.compiler.source>
18
        <maven.compiler.target>1.7</maven.compiler.target>
19
        <failOnMissingWebXml>false</failOnMissingWebXml>
20
    </properties>
21
</project>
22
​
Section 3

Activating and configuring CDI

In Java EE 7, CDI is activated automatically: you don’t need to add anything to your application to have CDI ready in it.

When your app is launched, CDI will scan your application to find its components (i.e. managed beans); this mechanism is called bean discovery.

Types discovered by this mechanism will be analyzed by the container to check if they meet the requirements for becoming beans, as explained below. The bean discovery mode can be set by adding a beans.xml file in the module:

  • /META-INF/beans.xml for a JAR
  • /WEB-INF/beans.xml for a WAR

Bean discovery is defined for each module (e.g. JAR) of the application, also called “bean archive," and can have 3 modes:

  • Annotated (default mode when no beans.xml file is present): only classes having specific annotations called Bean Defining Annotations will be discovered
  • All: all of the classes will be discovered
  • None: none of the classes will be discovered

Keep in mind that there is no global configuration for bean discovery, it is set only for the current bean archive.

Example of a beans.xml file setting bean discovery mode to all

8
1
<?xml version="1.0" encoding="UTF-8"?>
2
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
3
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4
       xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
5
                           http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
6
       version="1.1" bean-discovery-mode="all">
7
</beans>
8
​

Bean-Defining annotations

When a bean archive has its bean discovery mode set to Annotated (the default mode when no beans.xml is present), only the types with one of these annotations will be discovered:

  • @ApplicationScoped, @SessionScoped, @ConversationScoped and @RequestScoped annotations
  • All other normal scope types
  • @Interceptor and @Decorator annotations
  • All stereotype annotations (i.e. annotations annotated with @Stereotype),
  • The @Dependent scope annotation.

Note that EJB session beans are an exception to the bean discovery mechanism as they are always discovered as CDI beans (unless explicitly excluded.)

Excluding types from discovery

Managed beans and session beans can be excluded from the discovered beans by adding the @Vetoed annotation on their defining class or package.

It can also be done in the beans.xml file as explained in the spec.

Section 4

The CDI container

The container is the heart of CDI: you can think of it as the invisible conductor of your application.

It checks all possible CDI code at boot time, so exceptions at runtime are very rare in CDI--you know that something is wrong in your code at launch.

The container manages your components' lifecycle and services. It’ll create class instances for you when needed and add CDI features on the provided object. This enriched object will be automatically destroyed when the scope it is bound to is destroyed.

That’s why you’ll never use the “new” operator on a bean class unless you want to forego all CDI features on the resulting instance.

Section 5

Beans and contextual instances

CDI, at the most basic level, revolves around the notion of beans. The container discovers them at startup time by scanning classes in the deployment. A bean is defined by a set of attributes obtained by reading annotations and type on the bean definition. As we said above, the CDI container is in charge of creating and destroying bean instances according to their context, hence the term contextual instance. The table below introduces these attributes--they’ll be detailed later in this Refcard.

Table 1. Beans attributes

Types set

The set of Java types that the bean provides. This set is used when performing typesafe resolution (find the candidate bean for an injection point).

Qualifiers

Developer-defined annotations . provide a typesafe way to distinguish between multiple beans sharing the same type. They are also used by the typesafe resolution mechanism.

Scope

Also known as “context”. Determines the lifecycle and visibility of a bean. The container uses this attribute to know when to create and destroy a bean instance.

Alternative status

A bean can be defined as an alternative for an other bean. This feature can be used to simplify test creation, for instance.

Name

This optional value, is the only way to resolve a bean in a non typesafe way (i.e. with a String identifier). It allows bean access from the UI layer (JSF or JSP) or when integrating a legacy framework with CDI.

Section 6

Bean vs. Contextual instances

In a lot of blog posts and documentation, the term Bean is often used instead of contextual instance. It’s important to understand the difference. A bean is a collection of metadata associated with some code (usually a class) used by the container to provide a contextual instance. A contextual instance is the object that the container creates from the Bean attributes when an injection point has to be satisfied.

In short, unless you’re developing an advanced CDI feature, your code will only deal with contextual instances at runtime.

Section 7

Defining an Injection Point

As we just said, contextual instances are created and managed by the CDI container. When creating such an instance, the container may perform injection of other instances in it if it has one or more injection point.

Keep in mind that injection occurs only when the instance is created by the container.

Injection points are declared using the @javax.inject.Inject annotation. @Inject can be used in 3 places:

Field injection

When a field is annotated with @Inject, the container will look for a bean with a matching type and will provide a contextual instance of this bean to set the field value.

Example: Injecting in private a field

9
1
**public** **class** **MyBean** {
2
​
3
@Inject
4
**private** HelloService service;
5
​
6
    **public** **void** displayHello() {
7
        display(service.hello();
8
    }
9
}

Constructor injection

Only one constructor in a bean class may be annotated with @Inject. All parameters of the constructor will be resolved by the container to invoke it.

Example: injecting in a constructor

9
1
public class MyBean {
2
    @Inject
3
    private HelloService service;
4
​
5
    public void displayHello() {
6
        display(service.hello();
7
    }
8
}
9
​

Method injection

A bean class can one or more methods annotated with @Inject. These methods are called initializer methods.

Example: injecting in a method

9
1
**public** **class** **MyBean** {
2
​
3
    **private** HelloService service;
4
​
5
    @Inject
6
    **public** **void** initService(HelloService service) {
7
        this.service = service;
8
    }
9
}

Other injection points

Two specific CDI elements always have injection point without the need of being annotated with @Inject:

  • Producer methods
  • Observer methods

See below for their usage.

Section 8

Different kinds of CDI beans

CDI provides different ways to define Beans. The type set of the bean will vary with its kind.

If needed, using the @Typed annotation on bean definition can further restrict this type set. Object will always be part of bean type set.

CDI is not affected by type erasure, so List and List will correctly be treated as two different types.

Managed beans

Managed beans are the most obvious kind of bean available in CDI. They are defined by a class declaration in a bean archive.

A class is eligible to become a managed bean if it follows the following conditions:

  • It is not a non-static inner class.
  • It is a concrete class, or is annotated with @Decorator.
  • It has an appropriate constructor - either:
    • The class has a constructor with no parameters, or
    • The class declares a constructor annotated with @Inject.

Note: If the class is in an implicit bean archive (no beans.xml or bean discovery set to annotated) it should also have at least one of the following annotations to become a CDI managed bean:

  • @ApplicationScoped, @SessionScoped, @ConversationScoped and @RequestScoped annotations
  • All other normal scope types
  • @Interceptor and @Decorator annotations
  • All stereotype annotations (i.e. annotations annotated with @Stereotype)
  • The @Dependent scope annotation

Bean types of a managed bean

The set of bean types for a given managed bean contains:

  • The bean class
  • Every superclass (including Object)
  • All interface the class implements directly or indirectly

Session beans (EJB)

Local stateless, singleton, or stateful EJBs are automatically treated as CDI session beans: they support injection, CDI scope, interception, decoration, and all other CDI services. Remote EJB and MDB types cannot be used as CDI beans.

When using EJB in CDI, you have the features of both specifications. You can for instance have asynchronous behavior and observer features in one bean.

Bean types of a session bean

The set of bean types for a given CDI session bean depends on its definition:

If the session bean has local interfaces, it contains:

  • All local interfaces of the bean
  • All super interfaces of these local interfaces
  • Object class

If the session bean has a no-interface view, it contains:

  • The bean class
  • Every superclass (including Object).

Examples

17
1
`@ConversationScoped`
2
`@Stateful`
3
**public** **class** **ShoppingCart** { ... } **(1)**
4
​
5
`@Stateless`
6
`@Named`("loginAction")
7
**public** **class** **LoginActionImpl** **implements** LoginAction {
8
... } **(2)**
9
​
10
​
11
`@ApplicationScoped`
12
`@Singleton` **(3)**
13
`@Startup` **(4)**
14
**public** **class** **bootBean** {
15
`@Inject`
16
MyBean bean;
17
}
  1. A stateful bean (with no-interface view) defined in @ConversationScoped scope. It has ShoppingCart and Object in its bean types.
  2. A stateless bean in @Dependent scope with a view. Usable in EL with name “loginAction”. It has LoginAction in its bean types.
  3. It’s javax.ejb.Singleton defining a singleton session bean.
  4. The EJB will be instantiated at startup triggering instantiation of MyBean CDI bean.

Producers

Producers are the way to transform classes you don’t own into CDI beans.

By adding the @Produces annotation to a field or a non void method of a bean, you declare a new producer and so a new Bean.

Fields or methods defining a producer may have any modifier--even static.

Parameters in producer methods become injection points, and are resolved by the container before invocation.

Producers are also used to defined Java EE resources (like Persistence Context or Resource) as a CDI bean.

Bean types of a producer

It depends on the type of the producer (field type or method returned type):

  • If it’s an interface, the bean type set will contain the interface all interface it extends (directly or indirectly) and Object.
  • If it’s a primitive or array type, the set will contain the type and Object.
  • If it’s a class, the set will contains the class, every superclass, and all interfaces it implements (directly or indirectly).

Examples

13
1
**public** **class** **ProducerBean** {
2
​
3
`@Produces`
4
`@ApplicationScoped`
5
**private** List mapInt = **new** ArrayList();
6
**(1)**
7
​
8
`@Produces` `@RequestScoped` `@UserDatabase`
9
**public** EntityManager create(EntityManagerFactory emf) { **(2)**
10
**return** emf.createEntityManager();
11
}
12
​
13
}
  1. This producer field defines a bean with Bean types List, Collection, Iterable and Object
  2. This producer method defines an EntityManager with @UserDatabase qualifier in @RequestScoped from an EntityManagerFactory bean produced elsewhere.
Section 9

Qualifiers

Sometimes an injection point has more than one bean candidate for injection.

For instance, the following code will cause startup to fail with an "Ambiguous dependency" error:

An ambiguous injection point

22
1
**public** **class** **MyBean** {
2
`@Inject`
3
HelloService service; **(1)**
4
}
5
​
6
**public** **interface** **HelloService** {
7
    **public** String hello();
8
}
9
​
10
**public** **class** **FrenchHelloService** **implements**
11
HelloService {
12
    **public** String hello() { 
13
**return** "Bonjour tout le monde!";
14
}
15
}
16
​
17
**public** **class** **EnglishHelloService** **implements**
18
HelloService {
19
    **public** String hello() {
20
**return** "Hello World!";
21
    }
22
}
  1. Both implementations of HelloService are candidates for injection here

When bean type is not enough to resolve a bean, we can create a qualifier and add it to a bean. Because qualifiers are annotations, you maintain the benefits of the CDI strong typing approach.

One qualifier by language

11
1
`@Qualifier`
2
`@Retention`(RUNTIME)
3
`@Target`({FIELD, TYPE, METHOD, PARAMETER})
4
**public** `@interface` French {
5
}
6
​
7
`@Qualifier`
8
`@Retention`(RUNTIME)
9
`@Target`({FIELD, TYPE, METHOD, PARAMETER})
10
**public** `@interface` English {
11
}

Qualifiers are used on bean definitions or injection points.

26
1
`@French`
2
**public** **class** **FrenchHelloService** **implements**
3
HelloService {
4
    **public** String hello() {
5
        **return** "Bonjour tout le monde!";
6
    }
7
}
8
​
9
`@English`
10
**public** **class** **EnglishHelloService** **implements**
11
HelloService {
12
    **public** String hello() {
13
        **return** "Hello World!";
14
    }
15
}
16
​
17
**public** **class** **MyBean** {
18
    `@Inject`
19
`@French`
20
HelloService serviceFr;
21
​
22
`@Inject`
23
`@English`
24
HelloService serviceEn;
25
​
26
}

To match a given bean, an injection point must have a non-empty subset of the bean qualifiers (and of course a type present in its typeset.

Qualifiers can also have members. We could have solved our language problem like this:

A qualifier to qualify the language of the bean

37
1
`@Qualifier`
2
`@Retention`(RUNTIME)
3
`@Target`({FIELD, TYPE, METHOD, PARAMETER})
4
**public** `@interface` Language {
5
​
6
    LangChoice value();
7
​
8
    **public** **enum** LangChoice {
9
        FRENCH, ENGLISH
10
    }
11
}
12
​
13
`@Language`(FRENCH)
14
**public** **class** **FrenchHelloService** **implements**
15
HelloService {
16
    **public** String hello() { 
17
**return** "Bonjour tout le monde!";
18
}
19
}
20
​
21
`@Language`(ENGLISH)
22
**public** **class** **EnglishHelloService** **implements**
23
HelloService {
24
    **public** String hello() {
25
**return** "Hello World!";
26
    }
27
}
28
​
29
**public** **class** **MyBean** {
30
    `@Inject`
31
`@Language`(value = FRENCH)
32
HelloService serviceFr;
33
​
34
`@Inject`
35
`@Language`(value = ENGLISH)
36
HelloService serviceEn;
37
}

@Nonbinding annotations can be applied to a qualifier member to exclude it from the qualifier resolution.

A qualifier with a non binding member

8
1
`@Qualifier`
2
`@Retention`(RUNTIME)
3
`@Target`({FIELD, TYPE, METHOD, PARAMETER})
4
**public** `@interface` MyQualifier {
5
​
6
`@Nonbinding`
7
    String comment(); **(1)**
8
}
  1. The CDI container will treat two instances of MyQualifier with different comment() values as the same qualifier.

Built-in qualifiers

CDI includes the following built-in qualifiers:

Table 2. Built-in qualifiers

@Named

set bean name for weak typed environment (EL, Javascript)

@Default

added to all beans without other qualifiers, or having only the @Named qualifier

@Any

added to all beans for programmatic lookup and decorators

@Initialized

to qualify events when a context is started

@Destroyed

to qualify events when a context is destroyed

@Dependent (default) bean has the same scope as the one in which it’s injected @ApplicationScoped instance is linked to application lifecycle @SessionScoped instance is linked to http session lifecycle @RequestScoped instance is liked to http request lifecycle @ConversationScoped lifecycle manually controlled within session

scope examples

12
1
**public** **class** **BaseHelloService** **implements** HelloService
2
{ ... } **(1)**
3
​
4
`@RequestScoped` **(2)**
5
**public** **class** **RequestService** {
6
`@Inject` HelloService service;
7
}
8
​
9
`@ApplicationScoped` **(3)**
10
**public** **class** **ApplicationService** {
11
`@Inject` RequestService service; **(4)**
12
}
  1. Bean has default scope @Dependent, instances are created for each injection
  2. Bean is @RequestScoped. Instance is created by request context and destroyed with request context
  3. Bean is @ApplicationScoped. Instance is created by application context and will live for the duration of the application itself
  4. No problem to inject bean from another scope: CDI will provide the right bean
Section 10

Typesafe resolution

When resolving beans for a given injection point, the container considers the set of types and qualifiers of all available beans to find the right candidate.

Figure 1. A simplified version of typesafe resolution process

The actual process is a bit more complex with integration of Alternatives, but the general idea is here.

If the container succeeds in resolving the injection point by finding one and only one eligible bean, the create() method of this bean will be used to provide an instance for it.

Section 11

Programmatic lookup

Sometimes it is useful to resolve a bean at runtime or find all beans that match a given type. Programmatic lookup brings this powerful feature thanks to the Instance interface.

Request an instance at runtime with Instance

10
1
**public** **class** **MyBean** {
2
​
3
    `@Inject`
4
Instance services; **(1)**
5
​
6
    **public** **void** displayHello() {
7
**if**(!(services.isUnsatisfied() || services.isAmbiguous())) **(2)**
8
display(services.get().hello()); **(3)**
9
    }
10
}
  1. Instance injection points are always satisfied and never fail at deployment time
  2. Instance provides test methods to know if requesting an instance is safe
  3. With Instance you control when a bean instance is requested with the get() method

As instance extends the Iterable interface, you can use it to loop on instances of all beans of the specified type and qualifiers.

12
1
**public** **class** **MyBean** {
2
​
3
    `@Inject`
4
`@Any` **(1)**
5
Instance services;
6
​
7
    **public** **void** displayHello() {
8
        **for** (HelloService service : services) {
9
            display(service.hello());
10
        }
11
    }
12
}
  1. All beans have @Any qualifier so this injection point gets an Instance pointing to all beans having the type HelloService

Finally, programmatic lookup helps you to select a bean by its type and qualifier.

12
1
**public** **class** **MyBean** {
2
​
3
    `@Inject`
4
`@Any`
5
Instance services;
6
​
7
    **public** **void** displayHello() {
8
        display(
9
            services.select(**new** AnnotationLiteral()
10
{}).get()); **(1)**
11
    }
12
}
  1. Select() also accepts a type

The CDI spec provides the AnnotationLiteral and TypeLiteral classes to help you create instances of an annotation or parameterized type.

Section 12

Accessing CDI from non-CDI code

When you need to retrieve a CDI bean from non-CDI code, the CDI class is the easiest way:

Using CDI.current() to access the bean graph

12
1
**public** **class** **NonManagedClass** {
2
​
3
**public** HelloService getHelloService() {
4
Instance services =
5
CDI.current().select(HelloService.class,**new**
6
AnnotationLiteral() {});
7
**if** (!(services.isUnsatisfied || services.isAmbiguous))
8
**return** services.get();
9
**else**
10
**return** null;
11
}
12
}

The CDI.current() static method returns a CDI object that extends Instance. As all beans have Object in their type set, it allows you to perform a programmatic lookup on your entire beans collection.

CDI can also return the BeanManager--a class giving you access to advanced CDI features, including bean resolution.

For backwards compatibility, the BeanManager is also accessible through JNDI with the name java:comp/BeanManager.

You can learn more on BeanManager in the spec.

Section 13

Events

Events provide a mechanism for loosely coupled communication between components. An event consists of an event type, which may be any Java object, and optional event qualifiers.

The event object

Events are managed through instances of javax.enterprise.event.Event. Event objects are injected based on the event type.

2
1
`@Inject` Event normalEvent;
2
`@Inject` `@Admin` Event adminEvent;

Events are fired by calling fire() with an instance of the event type to be passed to observers.

1
1
event.fire(**new** LoggedInEvent(username));

Observers

Observers listen for events with observer methods. An observer methods should be defined in a bean, and must have one of its parameters annotated with @javax.enterprise.event.Observes--the annotated parameter defines the type to be observed.

Additional parameters to an observer method are normal CDI injection points.

8
1
**public** **void** afterLogin(`@Observes` LoggedInEvent event) {
2
​
3
}
4
​
5
**public** **void** afterAdminLogin(`@Observes` `@Admin` LoggedInEvent
6
event) {
7
​
8
}

Conditional observers

If a contextual instance of a bean with an observer method doesn’t exist when the corresponding event is fired, the container will create a new instance to handle the event. This behavior is controllable using the receive value of @Observes.

Table 4. Values of receive member in @Observes

Reception value Meaning
IF_EXISTS The observer method is only called if an instance of the component already exists.
ALWAYS The observer method is always called. If an instance doesn’t exist, one will be created. This is the default value.

Transactional observer

Event observers are normally processed when the event is fired. For transactional methods, however, it is often desirable for the event to fire at a certain point in the transaction lifecycle, such as after the transaction completes. This is specified with the during value of @Observes.

If a transaction phase is specified but no transaction is active, the event is fired immediately.

Table 5. Values of during member in @Observes

TransactionPhase value Meaning
IN_PROGRESS The event is called when it is fired, without regard to the transaction phase. This is the default value.
BEFORE_COMPLETION The event is called during the before completion phase of the transaction.
AFTER_COMPLETION The event is called during the after completion phase of the transaction.
AFTER_FAILURE The event is called during the after completion phase of the transaction, but only when the transaction fails.
AFTER_SUCCESS The event is called during the after completion phase of the transaction, but only when the transaction completes successfully.
Section 14

Interceptors and Decorators

CDI supports two mechanisms for dynamically adding or modifying the behavior of beans: interceptors and decorators.

Interceptors

Interceptors provide a mechanism for implementing functionality across multiple beans, and bean methods, that is orthogonal to the core function of those beans.

It is often used for non-business features like logging or security. For instance, in Java EE 7 the JTA specification provides the @Transactional interceptor to control transactions for the current invocation.

Interceptor Binding Type

An interceptor binding is an annotation annotated with the @javax.interceptor.InterceptorBinding meta-annotation.

Its goal is to bind the interceptor code to the bean or method to intercept.

defining an interceptor binding

6
1
`@Inherited`
2
`@Target`({TYPE, METHOD})
3
`@Retention`(RUNTIME)
4
`@InterceptorBinding`
5
**public** `@interface` Loggable {
6
}

Interceptor definition

An interceptor is a bean declared with the @javax.interceptor.Interceptor annotation.

Its matching interceptor binding should also be added to its declaration.

Since CDI 1.1, the interceptor can be enabled with @javax.annotation.Priority annotation--this defines its resolution order.

Method interceptors should have a method annotated @javax.interceptor.AroundInvoke that takes the javax.interceptor.InvocationContext as a parameter.

Defining an interceptor

10
1
`@Interceptor`
2
`@Loggable` **(1)**
3
`@Priority`(Interceptor.Priority.APPLICATION) **(2)**
4
**public** **class** **TransactionInterceptor** {
5
​
6
`@AroundInvoke` **(3)**
7
**public** Object logMethod(InvocationContext ctx) {
8
*// …*
9
}
10
}
  1. The interceptor binding to bind this code to this annotation
  2. The @Priority annotation to enable and prioritize the interceptor.
  3. The @AroundInvoke annotation indicates which method does the interception

Using interceptors

Thanks to interceptor binding it is very easy to apply an interceptor to bean or method.

14
1
**public** **class** **MyBean** {
2
`@Logabble`
3
**public** **void** doSomething() {
4
....
5
}
6
}
7
​
8
`@Logabble`
9
**public** **class** **MyOtherBean** {
10
​
11
**public** **void** doSomething() {
12
....
13
}
14
}

When applied on a bean, all the bean’s methods will be intercepted.

Activating and ordering interceptors

In Java EE 7 the easiest way to activate an interceptor in to use the @Priority annotation.

It is also possible to do it in beans.xml file as explained in the spec.

Decorators

Decorators also dynamically extend beans but with a slightly different mechanism than interceptors. Where interceptors deliver functionality orthogonal to potentially many beans, decorators extend the functionality of a single bean-type with functionality that is specific to that type.

Decorators are an easy way to change the business operation of an existing bean.

A decorator is a bean annotated with @javax.decorator.Decorator.

A decorator only decorates the interfaces that it implements (i.e. to be decorated a bean must implement an interface).

Example: a decorator firing an event in addition of expected code execution

17
1
`@Decorator` **(1)**
2
`@Priority`(Interceptor.Priority.APPLICATION) **(2)**
3
**public** **abstract** **class** **EventingDecorator** **implements**
4
MyBusiness **(3)**
5
{
6
`@Inject`
7
`@Delegate` **(4)**
8
MyBusiness business;
9
​
10
`@Inject`
11
Event evt;
12
​
13
**public** **void** doSomething(String message) {
14
business.doSomething(message);
15
evt.fire(message)
16
}
17
}
  1. The decorator is defined with the matching annotation
  2. Decorators are enabled and prioritized like interceptors
  3. As all methods don’t have to be decorated (i.e. implemented), the decorator is allowed to be an abstract class
  4. The decorated bean is injected with the specific @Delegate annotation.

A decorator must declare a single delegate injection point annotated @javax.decorator.Delegate. The delegate injection point is the bean to be decorated. Any calls to the delegate object that correspond to a decorated type will be called on the decorator, which may in turn invoke the method directly on the delegate object. The decorator bean does not need to implement all methods of the decorated types and may be abstract.

Activating and ordering decorators

In Java EE 7 the easiest way to activate a decorator in to use the @Priority annotation.

It is also possible to activate a decorator in beans.xml, as explained in the spec.

Decorators are always called after interceptors.

Section 15

Going further with CDI

This document is only an introduction to CDI--many topics are not covered here.

To go further, you can go to the learn section of the CDI specification website where a lot of resources are available to go deeper in CDI learning.

Like This Refcard? Read More From DZone

related article thumbnail

DZone Article

Resource Injection vs. Dependency Injection Explained!
related article thumbnail

DZone Article

Spring vs. Jakarta EE: Injecting Dependencies
related article thumbnail

DZone Article

How to Convert XLS to XLSX in Java
related article thumbnail

DZone Article

Automatic Code Transformation With OpenRewrite
related refcard thumbnail

Free DZone Refcard

Java Application Containerization and Deployment
related refcard thumbnail

Free DZone Refcard

Introduction to Cloud-Native Java
related refcard thumbnail

Free DZone Refcard

Java 15
related refcard thumbnail

Free DZone Refcard

Java 14

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: