How do I listen for an event?

An event is consumed by an observer method, and we inform Weld that our method is used to observe an event by annotating a parameter of the method, the event parameter, with @Observes. The type of event parameter is the event type we want to observe, and we may specify qualifiers on the event parameter to narrow what events we want to observe.

We may have an observer method for all events produced about a Book event type, as follows:

public void onBookEvent(@Observes Book book) { ... }

Or we may choose to only observe when a Book is removed, as follows:

public void onBookRemoval(@Observes @Removed Book book) { ... }

Note

Any additional parameters on an observer method are treated as injection points.

An observer method ...

Get JBoss Weld CDI for Java Platform now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.