Generic Top

I just announced the new Spring Boot 2 material, coming in REST With Spring:

>> CHECK OUT THE COURSE

1. Overview

CDI (Contexts and Dependency Injection) is the standard dependency injection framework of the Jakarta EE platform.

In this tutorial, we’ll take a look at CDI 2.0 and how it builds upon the powerful, type-safe injection mechanism of CDI 1.x by adding an improved, full-featured event notification model.

2. The Maven Dependencies

To get started, we’ll build a simple Maven project.

We need a CDI 2.0-compliant container, and Weld, the reference implementation of CDI, is a good fit:

<dependencies>
    <dependency>
        <groupId>javax.enterprise</groupId>
        <artifactId>cdi-api</artifactId>
        <version>2.0.SP1</version>
    </dependency>
    <dependency>
        <groupId>org.jboss.weld.se</groupId>
        <artifactId>weld-se-core</artifactId>
        <version>3.0.5.Final</version>
    </dependency>
</dependencies>

As usual, we can pull the latest versions of cdi-api and weld-se-core from Maven Central.

3. Observing and Handling Custom Events

Simply put, the CDI 2.0 event notification model is a classic implementation of the Observer pattern, based on the @Observes method-parameter annotation. Hence, it allows us to easily define observer methods, which can be automatically called in response to one or more events.

For instance, we could define one or more beans, which would trigger one or more specific events, while other beans would be notified about the events and would react accordingly.

To demonstrate more clearly how this works, we’ll build a simple example, including a basic service class, a custom event class, and an observer method that reacts to our custom events.

3.1. A Basic Service Class

Let’s start by creating a simple TextService class:

public class TextService {

    public String parseText(String text) {
        return text.toUpperCase();
    }
}

3.2. A Custom Event Class

Next, let’s define a sample event class, which takes a String argument in its constructor:

public class ExampleEvent {
    
    private final String eventMessage;

    public ExampleEvent(String eventMessage) {
        this.eventMessage = eventMessage;
    }
    
    // getter
}

3.3. Defining an Observer Method with the @Observes Annotation

Now that we’ve defined our service and event classes, let’s use the @Observes annotation to create an observer method for our ExampleEvent class:

public class ExampleEventObserver {
    
    public String onEvent(@Observes ExampleEvent event, TextService textService) {
        return textService.parseText(event.getEventMessage());
    } 
}

While at first sight, the implementation of the onEvent() method looks fairly trivial, it actually encapsulates a lot of functionality through the @Observes annotation.

As we can see, the onEvent() method is an event handler that takes ExampleEvent and TextService objects as arguments.

Let’s keep in mind that all the arguments specified after the @Observes annotation are standard injection points. As a result, CDI will create fully-initialized instances for us and inject them into the observer method.

3.4. Initializing our CDI 2.0 Container

At this point, we’ve created our service and event classes, and we’ve defined a simple observer method to react to our events. But how do we instruct CDI to inject these instances at runtime?

Here’s where the event notification model shows its functionality to its fullest. We simply initialize the new SeContainer implementation and fire one or more events through the fireEvent() method:

SeContainerInitializer containerInitializer = SeContainerInitializer.newInstance(); 
try (SeContainer container = containerInitializer.initialize()) {
    container.getBeanManager().fireEvent(new ExampleEvent("Welcome to Baeldung!")); 
}

Note that we’re using the SeContainerInitializer and SeContainer objects because we’re using CDI in a Java SE environment, rather than in Jakarta EE.

All the attached observer methods will be notified when the ExampleEvent is fired by propagating the event itself.

Since all the objects passed as arguments after the @Observes annotation will be fully initialized, CDI will take care of wiring up the whole TextService object graph for us, before injecting it into the onEvent() method.

In a nutshell, we have the benefits of a type-safe IoC container, along with a feature-rich event notification model.

4. The ContainerInitialized Event

In the previous example, we used a custom event to pass an event to an observer method and get a fully-initialized TextService object.

Of course, this is useful when we really need to propagate one or more events across multiple points of our application.

Sometimes, we simply need to get a bunch of fully-initialized objects that are ready to be used within our application classes, without having to go through the implementation of additional events.

To this end, CDI 2.0 provides the ContainerInitialized event class, which is automatically fired when the Weld container is initialized.

Let’s take a look at how we can use the ContainerInitialized event for transferring control to the ExampleEventObserver class:

public class ExampleEventObserver {
    public String onEvent(@Observes ContainerInitialized event, TextService textService) {
        return textService.parseText(event.getEventMessage());
    }    
}

And keep in mind that the ContainerInitialized event class is Weld-specific. So, we’ll need to refactor our observer methods if we use a different CDI implementation.

5. Conditional Observer Methods

In its current implementation, our ExampleEventObserver class defines by default an unconditional observer method. This means that the observer method will always be notified of the supplied event, regardless of whether or not an instance of the class exists in the current context.

Likewise, we can define a conditional observer method by specifying notifyObserver=IF_EXISTS as an argument to the @Observes annotation:

public String onEvent(@Observes(notifyObserver=IF_EXISTS) ExampleEvent event, TextService textService) { 
    return textService.parseText(event.getEventMessage());
}

When we use a conditional observer method, the method will be notified of the matching event only if an instance of the class that defines the observer method exists in the current context.

6. Transactional Observer Methods

We can also fire events within a transaction, such as a database update or removal operation. To do so, we can define transactional observer methods by adding the during argument to the @Observes annotation.

Each possible value of the during argument corresponds to a particular phase of a transaction:

  • BEFORE_COMPLETION
  • AFTER_COMPLETION
  • AFTER_SUCCESS
  • AFTER_FAILURE

If we fire the ExampleEvent event within a transaction, we need to refactor the onEvent() method accordingly to handle the event during the required phase:

public String onEvent(@Observes(during=AFTER_COMPLETION) ExampleEvent event, TextService textService) { 
    return textService.parseText(event.getEventMessage());
}

A transactional observer method will be notified of the supplied event only in the matching phase of a given transaction.

7. Observer Methods Ordering

Another nice improvement included in CDI 2.0’s event notification model is the ability for setting up an ordering or priority for calling observers of a given event.

We can easily define the order in which the observer methods will be called by specifying the @Priority annotation after @Observes.

To understand how this feature works, let’s define another observer method, aside from the one that ExampleEventObserver implements:

public class AnotherExampleEventObserver {
    
    public String onEvent(@Observes ExampleEvent event) {
        return event.getEventMessage();
    }   
}

In this case, both observer methods by default will have the same priority. Thus, the order in which CDI will invoke them is simply unpredictable.

We can easily fix this by assigning to each method an invocation priority through the @Priority annotation:

public String onEvent(@Observes @Priority(1) ExampleEvent event, TextService textService) {
    // ... implementation
}
public String onEvent(@Observes @Priority(2) ExampleEvent event) {
    // ... implementation
}

Priority levels follow a natural ordering. Therefore, CDI will call first the observer method with a priority level of 1 and will invoke second the method with a priority level of 2.

Likewise, if we use the same priority level across two or more methods, the order is again undefined.

8. Asynchronous Events

In all the examples that we’ve learned so far, we fired events synchronously. However, CDI 2.0 allows us to easily fire asynchronous events as well. Asynchronous observer methods can then handle these asynchronous events in different threads.

We can fire an event asynchronously with the fireAsync() method:

public class ExampleEventSource {
    
    @Inject
    Event<ExampleEvent> exampleEvent;
    
    public void fireEvent() {
        exampleEvent.fireAsync(new ExampleEvent("Welcome to Baeldung!"));
    }   
}

Beans fire up events, which are implementations of the Event interface. Therefore, we can inject them as any other conventional bean.

To handle our asynchronous event, we need to define one or more asynchronous observer methods with the @ObservesAsync annotation:

public class AsynchronousExampleEventObserver {

    public void onEvent(@ObservesAsync ExampleEvent event) {
        // ... implementation
    }
}

9. Conclusion

In this article, we learned how to get started using the improved event notification model bundled with CDI 2.0.

As usual, all the code samples shown in this tutorial are available over on GitHub.

Generic bottom

I just announced the new Spring Boot 2 material, coming in REST With Spring:

>> CHECK OUT THE LESSONS

Leave a Reply

avatar
  Subscribe  
Notify of