Using Application Events
An event is class-derived from ApplicationEvent, which itself derives from java.util.EventObject. Any
bean can listen for events by implementing the ApplicationListener<T> interface; the ApplicationContext
automatically registers any bean that implements this interface as a listener when it is configured. Events
are published using the ApplicationEventPublisher.publishEvent() method, so the publishing class must
have knowledge of the ApplicationContext (which extends the ApplicationEventPublisher interface). In a
web application, this is simple because many of your classes are derived from Spring Framework classes
that allow access to the ApplicationContext through a protected method. In a stand-alone application,
you can have your publishing bean implement ApplicationContextAware to enable it to publish events.
Listing 5-37 shows an example of a basic event class.
Listing 5-37. Creating an Event Class
package com.apress.prospring3.ch5.event;
import org.springframework.context.ApplicationEvent;
public class MessageEvent extends ApplicationEvent {
private String msg;
public MessageEvent(Object source, String msg) {
super(source);
this.msg = msg;
}
public String getMessage() {
return msg;
}
}
This code is quite basic; the only point of note is that the ApplicationEvent has a single constructor
that accepts a reference to the source of the event. This is reflected in the constructor for MessageEvent.
In Listing 5-38 you can see the code for the listener.
Listing 5-38. The MessageEventListener Class
package com.apress.prospring3.ch5.event;
import org.springframework.context.ApplicationListener;
public class MessageEventListener implements ApplicationListener<MessageEvent> {
public void onApplicationEvent(MessageEvent event) {
MessageEvent msgEvt = (MessageEvent) event;
System.out.println("Received: " + msgEvt.getMessage());
}
}
The ApplicationListener interface defines a single method, onApplicationEvent, that is called by
Spring when an event is raised. The MessageEventListener shows its interest only in events of type
MessageEvent (or its subclasses) by implementing the strongly typed ApplicationListener interface. If a
MessageEvent was received, it writes the message to stdout. Publishing events is simple; it is just a matter
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home