Jakarta (Java) EE 8 Observer Example

CDI 2.0 Observer

The observer pattern is very when you want to perform actions based on events that are being fired in your application. To implement the pattern with CDI in the Jakarta EE 8 api you will need to add the following pieces:

  • Event
  • Trigger
  • Listener

Event

The javax.enterprise.event.Event is what you will need to inject into the bean that will be performing the action you want to observe. For example:

@Path("dembeans")
@Stateless
public class MyFavoriteBean {

    @Inject Event mySpecialEvent;
...
}

Trigger

The trigger will fire the event for the Listener to observe. Event interface has to version as of Jakarta EE 8, fire(T Event) which is the blocking version and fireAsync( U event ) for the asynchronous call.

@Path("dembeans")
@Stateless
public class MyFavoriteBean {

    @Inject Event<MySpecialEvent> mySpecialEvent;

    @POST
    @Path("new")
    public Response createSalesOrder(){
         //Doing amazing things in this part of the code
         mySpecialEvent.fireAsync(new MySpecialEvent())
    }
...
}

Listener

The Listener object is where the magic happens. You will need a method that has a @Observer or @ObserverAsync injection point. The method can then perform whatever action that need to be done following the triggering event.

@Singleton
public class MySpecialEventListener {
    
    public void onMySpecialEvent(@ObservesAsync MySpecialEvent event){
        
        //Do something amazing
        ........
    }
}

Wrapping up..

I have a full working example project on my Github repo if you want to see the code in action. The code snippets to focus on are in com.heathcasey.jakeeobserverpattern.boundry.SalesOrder.java and com.heathcasey.jakeeobserverpattern.controller.SalesOrderCreatedListener.java