In this post I will show you how to produce a CDI event and how to handle it even if it is deployed in another application.
The Event class
|
1 2 3 4 5 6 7 8 9 10 11 |
public class LoggerEvent { private String message; public LoggerEvent(String message) { this.message = message; } public String getMessage() { return message; } } |
A simple JSF Page
|
1 2 3 4 5 6 7 8 9 10 11 |
<?xml version='1.0' encoding='UTF-8' ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://xmlns.jcp.org/jsf/html"> <h:head> <title>CDI Event Example</title> </h:head> <h:body> <h1>#{controller.message}</h1> </h:body> </html> |
This page only shows a simple message from the backing bean (the call to the bean produces the bean’s initialization).
Backing Bean
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import javax.annotation.PostConstruct; import javax.enterprise.context.RequestScoped; import javax.enterprise.event.Event; import javax.inject.Inject; import javax.inject.Named; @Named @RequestScoped public class Controller { @Inject private Event<LoggerEvent> event; private String message = "CDI Events Example"; @PostConstruct public void init() { event.fire(new LoggerEvent("Hello from CDI events")); } public String getMessage() { return message; } } |
Here we Inject an event (LoggerEvent) via CDI Inject annotation. Then inside the init method annotated with PostConstruct we fire the event with a new instance of the event. This is the simplest way to fire a CDI event. No matter who are listening to this event will be notified.
A simple Logger Event Handler
|
1 2 3 4 5 6 7 8 9 10 11 12 |
import java.util.logging.Level; import java.util.logging.Logger; import javax.ejb.Stateless; import javax.enterprise.event.Observes; @Stateless public class LoggerEventHandler { public void log(@Observes LoggerEvent event) { Logger.getLogger("LoggerEventHandler.class").log(Level.INFO, event.getMessage()); } } |
This class will listen for events annotated with the keyword @Observes. Because of this, it will execute the method. In this case it will print to the console a log message passed to the constructor of the event instance when it was created: Hello from CDI events as you can see in the next picture.
Result (console result)

AS you can see, it’s just that simple to create a CDi event and listen to it. This technique uses the Observer design pattern here with the help of @Observes annotation.
Feel free to comment. Download the souce code CDIEvents.
Thanks.