Simple CDI Events Example

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

public class LoggerEvent {
	private String message;

	public LoggerEvent(String message) {
		this.message = message;
	}

	public String getMessage() {
		return message;
	}
}

A simple JSF Page

<?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

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

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)

cdi events
cdi events

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.

Leave a Reply

Your email address will not be published. Required fields are marked *