Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 36 ยท Dependency Injection and CDI

Events and Bean Lifecycle

Decouple Quarkus components with CDI events and observers, run code at startup and shutdown with StartupEvent and @Startup, and use @PostConstruct and @PreDestroy.

When an order is placed, several things may need to happen: send an email, update statistics, notify a warehouse. If the order service calls each of them directly, it knows too much and changes whenever a new reaction is added. CDI events solve this. The order service fires an OrderPlaced event and does not know who listens. Each listener is an observer in its own class.

This lesson covers events and observers, asynchronous events, the application lifecycle events Quarkus fires at startup and shutdown, and the bean lifecycle callbacks @PostConstruct and @PreDestroy. The real code is read-only. The runnable examples are plain-Java stand-ins of an event bus and a bean lifecycle.

Firing and observing events

An event can be any Java object. Define one, preferably as a record:

Java
public record OrderPlaced(long orderId, String customer, long cents) {}

Fire it through an injected Event<T>:

Java
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Event;
import jakarta.inject.Inject;

@ApplicationScoped
public class OrderService {

    @Inject
    Event<OrderPlaced> orderPlaced;

    public void place(long id, String customer, long cents) {
        // ... save the order ...
        orderPlaced.fire(new OrderPlaced(id, customer, cents));
    }
}

Any bean can observe it with a method parameter annotated @Observes:

Java
@ApplicationScoped
public class EmailSender {
    void onOrder(@Observes OrderPlaced event) {
        // send a confirmation to event.customer()
    }
}

@ApplicationScoped
public class Statistics {
    void onOrder(@Observes OrderPlaced event) {
        // update counters
    }
}

fire is synchronous: all observers run, in the same thread, before fire returns. An exception thrown by an observer propagates to the caller of fire. Observers are found by event type (including supertypes), so an observer of Object would see everything.

Events decouple code

Fire The producer announces what happened.
Observe Interested beans react independently.
Extend Add a listener without editing the producer.

The producer never knows who is listening.

1 / 2

Ordering, qualifiers and async

You can order observers with @Priority on the event parameter (lower values run first; the default is 2500):

Java
void first(@Observes @Priority(10) OrderPlaced e) { /* runs early */ }
void later(@Observes @Priority(100) OrderPlaced e) { /* runs after */ }

Qualifiers narrow events the same way as beans. Fire @Inject @Urgent Event<OrderPlaced> and only observers marked @Observes @Urgent OrderPlaced hear it. You can also add a qualifier at fire time with event.select(new Urgent.Literal()).fire(...).

Asynchronous events use fireAsync and @ObservesAsync. Observers run on a different thread and the caller does not wait:

Java
orderPlaced.fireAsync(new OrderPlaced(id, customer, cents))
    .whenComplete((event, failure) -> {
        // failure is a CompletionException when an observer threw
    });
Java
void audit(@ObservesAsync OrderPlaced event) { /* runs on a worker thread */ }

An async observer does not see a request context from the caller by default, and it runs outside any transaction of the caller. Use asynchronous events for notifications that may be slow, and synchronous ones when the order matters.

Transactional observers (@Observes(during = TransactionPhase.AFTER_SUCCESS)) run only after the surrounding transaction committed, which is the right choice for "send email once the order is really stored":

Java
void afterCommit(@Observes(during = TransactionPhase.AFTER_SUCCESS) OrderPlaced event) {
    // the order is committed in the database now
}

An event bus stand-in

This stand-in is a tiny event bus. Observers register for a type with a priority; fire calls matching observers in priority order and also reaches observers of supertypes, like CDI. It shows why the producer needs no knowledge of the listeners.

Java Stand-in: events, observers and priorities

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Observers ran in priority order (10, 100, 2500, 5000). The Object observer caught every event, including the string. Adding a new reaction took one observe call and left the producer untouched.

Application lifecycle events

Quarkus fires two special events you can observe:

Java
import io.quarkus.runtime.ShutdownEvent;
import io.quarkus.runtime.StartupEvent;
import jakarta.enterprise.event.Observes;
import org.jboss.logging.Logger;

@ApplicationScoped
public class Lifecycle {

    private static final Logger LOG = Logger.getLogger(Lifecycle.class);

    void onStart(@Observes StartupEvent event) {
        LOG.info("The application is starting...");
    }

    void onStop(@Observes ShutdownEvent event) {
        LOG.info("The application is stopping...");
    }
}

StartupEvent fires when the application has started, which is a good place to load initial data or warm a cache. The bean that contains the observer is created at that moment.

The @Startup annotation is a shorter way to say "create this bean eagerly at startup":

Java
import io.quarkus.runtime.Startup;

@Startup
@ApplicationScoped
public class CacheWarmer {

    @PostConstruct
    void load() {
        // runs when the application starts, not on first use
    }
}

You can also put @Startup on a method of an application-scoped or singleton bean, or give it an ordering priority: @Startup(1000) (lower values run first).

Bean lifecycle callbacks

Two standard annotations mark methods the container calls around a bean's life:

Annotation When it runs
@PostConstruct After construction and injection, before the first business call
@PreDestroy Before the container discards the instance (application shutdown for singletons)
Java
@ApplicationScoped
public class ConnectionPool {

    private List<Connection> connections;

    @PostConstruct
    void open() {
        connections = new ArrayList<>();      // open resources here
    }

    @PreDestroy
    void close() {
        connections.forEach(Connection::close);   // release them here
    }
}

Use @PostConstruct for initialisation that needs injected fields (the constructor runs before injection of fields). Keep it fast: a slow callback delays the first request. For @Dependent beans, @PreDestroy runs when the owner is destroyed.

A lifecycle stand-in

This second stand-in recreates the callback order using annotations and reflection: build the object, run the @PostConstruct methods, use it, then run @PreDestroy on shutdown. The printed order is the one to memorise.

Java Stand-in: constructor, @PostConstruct, use, @PreDestroy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Note the constructor sees url as null: injected state is not available yet. That is the reason @PostConstruct exists.

A startup observer is also the right home for @ConfigProperty checks: fail fast with a clear message if a required setting is missing, rather than failing on the first request.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does Event<T>.fire(...) do?

    fire is synchronous. For asynchronous delivery use fireAsync with @ObservesAsync.
  2. 2. In which order do observers with @Priority run?

    Lower priority values run first. The default observer priority is 2500.
  3. 3. Why use @PostConstruct instead of the constructor for initialisation that needs injected fields?

    Fields are injected after construction, so only @PostConstruct (or constructor parameters) can rely on them.
  4. 4. Which statement about @Startup is true?

    Without it, an application-scoped bean is created lazily on first use. @Startup forces creation at startup.
  5. 5. When does an AFTER_SUCCESS transactional observer run?

    TransactionPhase.AFTER_SUCCESS waits for a successful commit, so side effects like emails happen only for data that was really stored.

Summary

  • Fire events with Event<T> and observe them with @Observes; the producer does not know its listeners.
  • Observers run in @Priority order (low first); fireAsync and @ObservesAsync run them on other threads.
  • StartupEvent, ShutdownEvent and @Startup run code at application start and stop.
  • @PostConstruct runs after injection, @PreDestroy before the bean is discarded.
  • Use transactional observers for effects that must follow a successful commit.

Next: REST Resources and Methods