Dynamic event qualifiers in CDI

CDI Events

CDI events allow your application components to communicate with each other in a loosely coupled manner. Those more familiar with JMS can also think of CDI events as a Synchronous equivalent of JMS (with Java EE 8, CDI 2.0 will offer asynchronous event mechanism).

Event Qualifiers

Events can be enriched using qualifiers. Think of these as message selectors (the concept is not very different from Message Selectors in JMS).

//firing a (statically) qualified event
private Event<RequestOutcome> outcomeEvent;
public void notify(){
public void handleApprovedRequest(@Observes @Approved RequestOutcome approvedOutcome){
public void handleRejectedRequest(@Observes @Rejected RequestOutcome rejectedOutcome){

Using Dynamic CDI event qualifiers

The above example demonstrates the static way of declaring qualifiers. CDI also provides a more dynamic version of the same feature (qualifier declaration).

private Event<RequestOutcome> outcomeEvent; //no qualifier specified
public void notify(){
RequestOutcome outcome = outcomeEvent.getOutcome();
Annotation qualifier = null;
//determine event qualifier dynamically
if(outcome == Outcome.APPROVED){
qualifier = new Approved();
else if(outcome == Outcome.REJECTED){
qualifier = new Rejected();
//fire the (dynamically qualified) event

Please note that you can specify multiple qualifiers with this mechanism

Other options

Although not discussed here, the Event interface also exposes couple of other methods to allow dynamic qualifier selection.

public <U extends T> Event<U> select(Class<U> subtype, Annotation… qualifiers);
public <U extends T> Event<U> select(TypeLiteral<U> subtype, Annotation… qualifiers);

The benefits are obvious…

The select method (and its overloaded counterparts) provide a flexible way of handling qualified events and helps avoid proliferation of injected Event instances for specific set of qualifiers.


About Abhishek

Loves Go, NoSQL DBs and messaging systems
This entry was posted in Java, Java EE and tagged , , . Bookmark the permalink.

2 Responses to Dynamic event qualifiers in CDI

  1. Pingback: Dynamic event qualifiers in CDI | Dinesh Ram Kali.

  2. Pingback: Java Weekly 1/16: GC Overhead, Monitor Microservices, CDI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s