of creating an instance of the event class and passing it to the ApplicationEventPublisher
.publishEvent() method, as shown in Listing 5-39.
Listing 5-39. Publishing an Event
package com.apress.prospring3.ch5.event;
import
org.springframework.beans.BeansException;
import
org.springframework.context.ApplicationContext;
import
org.springframework.context.ApplicationContextAware;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
public class Publisher implements ApplicationContextAware {
private ApplicationContext ctx;
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"classpath:events/events.xml");
Publisher pub = (Publisher) ctx.getBean("publisher");
pub.publish("Hello World!");
pub.publish("The quick brown fox jumped over the lazy dog");
}
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
this.ctx = applicationContext;
}
public void publish(String message) {
ctx.publishEvent(new MessageEvent(this, message));
}
}
Here you can see that the Publisher class retrieves an instance of itself from the ApplicationContext
and then, using the publish() method, publishes two MessageEvents to the ApplicationContext. The
Publisher bean instance accesses the ApplicationContext by implementing ApplicationContextAware.
Listing 5-40 shows the configuration for this example (events/events.xml).
Listing 5-40. Configuring ApplicationListener Beans
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<bean id="publisher" class="com.apress.prospring3.ch5.event.Publisher"/>
<bean id="messageEventListener"
class="com.apress.prospring3.ch5.event.MessageEventListener"/>
</beans>
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home