Thinking in Java EE (At Least Trying To!)

DZone 's Guide to

Thinking in Java EE (At Least Trying To!)

If you think of CDI events as a synchronous equivalent of JMS, it's a lot easier to wrap your head around.

· Java Zone ·
Free Resource

CDI events allow your application components to communicate with each other in a loosely coupled manner. Those more familiar you are with JMS, the more you can also think of CDI events as a synchronous equivalent of JMS (with Java EE 8, CDI 2.0 will offer an 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 example abobe 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 a 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 a specific set of qualifiers.

java ee ,java ,cdi

Published at DZone with permission of Abhishek Gupta , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}