Weld SiteCommunity Documentation

Chapter 11. Events

11.1. Event payload
11.2. Event observers
11.3. Event producers
11.3.1. Synchronous event producers
11.3.2. Asynchronous event producers
11.3.3. Applying qualifiers to event
11.4. Conditional observer methods
11.5. Event qualifiers with members
11.6. Multiple event qualifiers
11.7. Transactional observers

Dependency injection enables loose-coupling by allowing the implementation of the injected bean type to vary, either at deployment time or runtime. Events go one step further, allowing beans to interact with no compile time dependency at all. Event producers raise events that are delivered to event observers by the container.

This basic schema might sound like the familiar observer/observable pattern, but there are a couple of twists:

The CDI event notification facility uses more or less the same typesafe approach that we’ve already seen with the dependency injection service.

The event object carries state from producer to consumer. The event object is nothing more than an instance of a concrete Java class. (The only restriction is that an event type may not contain type variables). An event may be assigned qualifiers, which allows observers to distinguish it from other events of the same type. The qualifiers function like topic selectors, allowing an observer to narrow the set of events it observes.

An event qualifier is just a normal qualifier, defined using @Qualifier. Here’s an example:


public @interface Updated {}

An observer method is a method of a bean with a parameter annotated @Observes or @ObservesAsync.

public void onAnyDocumentEvent(@Observes Document document) { ... }

or in asynchronous version

public void onAnyDocumentEvent(@ObservesAsync Document document) { ... }

The annotated parameter is called the event parameter. The type of the event parameter is the observed event type, in this case Document. The event parameter may also specify qualifiers.

public void afterDocumentUpdate(@Observes @Updated Document document) { ... }

An observer method need not specify any event qualifiers—in this case it is interested in every event whose type is assignable to the observed event type. Such observer will trigger on both events shown below:

@Inject @Any Event<Document> documentEvent;

@Inject @Updated Event<Document> anotherDocumentEvent;

If the observer does specify qualifiers, it will be notified of an event if the event object is assignable to the observed event type, and if the set of observed event qualifiers is a subset of all the event qualifiers of the event.

The observer method may have additional parameters, which are injection points:

public void afterDocumentUpdate(@Observes @Updated Document document, User user) { ... }

Event producers fire events either synchronously or asynchronously using an instance of the parameterized Event interface. An instance of this interface is obtained by injection:

@Inject @Any Event<Document> documentEvent;

A producer raises asynchronous events by calling the fireAsync() method of the Event interface, passing the event object:


This particular event will only be delivered to asynchronous observer method that:

fireAsync method returns immediately and all the resolved asynchronous observers are notified in one or more different threads. If any observer method throws an exception, the container will suppress it and notify remaining observers. The resulting CompletionStage will then finish exceptionally with CompletionException containing all previously suppressed exceptions.

The Event.fireAsync() method may be called with a NotificationOptions parameter to configure the notification of asynchronous observer methods , e.g. to specify an Executor object to be used for asynchronous delivery. Weld defines the following non-portable notification options (see WeldNotificationOptions):

KeyValue typeDescription



The notification mode. Possible values are: SERIAL (default), PARALLEL. See also Notification modes.


Long or String which can be parsed as a long

The notification timeout (in milliseconds) after which the returned completion stage must be completed. If the time expires the stage is completed exceptionally with a CompletionException holding the java.util.concurrent.TimeoutException as its cause. The expiration does not abort the notification of the observers.

Table 11.1. Notification modes



Asynchronous observers are notified serially in a single worker thread (default behavior).


Asynchronous observers are notified in parallel assuming that the java.util.concurrent.Executor used supports parallel execution.

By default, if there is no instance of an observer in the current context, the container will instantiate the observer in order to deliver an event to it. This behavior isn’t always desirable. We may want to deliver events only to instances of the observer that already exist in the current contexts.

A conditional observer is specified by adding receive = IF_EXISTS to the @Observes annotation.

public void refreshOnDocumentUpdate(@Observes(receive = IF_EXISTS) @Updated Document d) { ... }

An event qualifier type may have annotation members:


public @interface Role {
   RoleType value();

The member value is used to narrow the messages delivered to the observer:

public void adminLoggedIn(@Observes @Role(ADMIN) LoggedIn event) { ... }

Event qualifier type members may be specified statically by the event producer, via annotations at the event notifier injection point:

@Inject @Role(ADMIN) Event<LoggedIn> loggedInEvent;

Alternatively, the value of the event qualifier type member may be determined dynamically by the event producer. We start by writing an abstract subclass of AnnotationLiteral:

abstract class RoleBinding

   extends AnnotationLiteral<Role>
   implements Role {}

The event producer passes an instance of this class to select():

documentEvent.select(new RoleBinding() {

   public void value() { return user.getRole(); }

Event qualifiers may be combined, for example:

@Inject @Blog Event<Document> blogEvent;

if (document.isBlog()) blogEvent.select(new AnnotationLiteral<Updated>(){}).fire(document);

The above shown event is fired with two qualifiers - @Blog and @Updated. An observer method is notified if the set of observer qualifiers is a subset of the fired event’s qualifiers. Assume the following observers in this example:

public void afterBlogUpdate(@Observes @Updated @Blog Document document) { ... }
public void afterDocumentUpdate(@Observes @Updated Document document) { ... }
public void onAnyBlogEvent(@Observes @Blog Document document) { ... }
public void onAnyDocumentEvent(@Observes Document document) { ... }}}

All of these observer methods will be notified.

However, if there were also an observer method:

public void afterPersonalBlogUpdate(@Observes @Updated @Personal @Blog Document document) { ... }

It would not be notified, as @Personal is not a qualifier of the event being fired. Or to put it more formally, @Updated and @Personal do not form a subset of @Blog and @Updated.

Transactional observers receive their event notifications during the before or after completion phase of the transaction in which the event was raised. For example, the following observer method needs to refresh a query result set that is cached in the application context, but only when transactions that update the Category tree succeed:

public void refreshCategoryTree(@Observes(during = AFTER_SUCCESS) CategoryUpdateEvent event) { ... }

There are five kinds of transactional observers:

Transactional observers are very important in a stateful object model because state is often held for longer than a single atomic transaction.

Imagine that we have cached a JPA query result set in the application scope:

import javax.ejb.Singleton;

import javax.enterprise.inject.Produces;
@ApplicationScoped @Singleton
public class Catalog {
   @PersistenceContext EntityManager em;
   List<Product> products;
   @Produces @Catalog
   List<Product> getCatalog() {
      if (products==null) {
         products = em.createQuery("select p from Product p where p.deleted = false")
      return products;

From time to time, a Product is created or deleted. When this occurs, we need to refresh the Product catalog. But we should wait until after the transaction completes successfully before performing this refresh!

The bean that creates and deletes `Product`s could raise events, for example:

import javax.enterprise.event.Event;

public class ProductManager {
   @PersistenceContext EntityManager em;
   @Inject @Any Event<Product> productEvent;
   public void delete(Product product) {
      productEvent.select(new AnnotationLiteral<Deleted>(){}).fire(product);
   public void persist(Product product) {
      productEvent.select(new AnnotationLiteral<Created>(){}).fire(product);

And now Catalog can observe the events after successful completion of the transaction:

import javax.ejb.Singleton;

@ApplicationScoped @Singleton
public class Catalog {
   void addProduct(@Observes(during = AFTER_SUCCESS) @Created Product product) {
   void removeProduct(@Observes(during = AFTER_SUCCESS) @Deleted Product product) {