View RSS Feed

Spring Framework

Listening for Events with Spring

Rate this Entry
by , 11-16-2011 at 04:03 PM (2828 Views)
During the application life cycle, the ApplicationContext will publish a handful of events that tell interested listeners what’s going on. All of these events are all subclasses of the abstract class org.springframework.context.ApplicationEvent. A couple of these subclasses are:
  • ContextClosedEvent—Published when the application context is closed
  • ContextRefreshedEvent—Published when the application context is initialized or refreshed
  • RequestHandledEvent—Published within a web application context when a request is handled



Most beans are uninterested in the events they are published. But sometimes, you might have a bean that might want to know about application events. If you do, all you need to do is implement the org.springframework.context.ApplicationListener interface which has as its one method, onApplicationEvent(), which is responsible for reacting to an application event:

p
Java Code:
ublic class CarListener implements ApplicationListener { 
public void onApplicationEvent(ApplicationEvent event) {
... 
     }
}
Now all you need to do is to tell Spring about an application event listener is to simply register it as a bean within the context:

Java Code:
<bean id="refreshListener" class="com.acme.springexample.domain.CarListener"/>
When Spring’s container loads the bean within the application context, it will notice that it implements an ApplicationListener and will call its onApplicationEvent() method when an event is published.

Submit "Listening for Events with Spring" to Facebook Submit "Listening for Events with Spring" to Digg Submit "Listening for Events with Spring" to del.icio.us Submit "Listening for Events with Spring" to StumbleUpon Submit "Listening for Events with Spring" to Google

Categories
Event

Comments