ApplicationContext是观察者模式的实现。
ApplicationEvent--事件容器
ApplicationListener--事件监听器(onApplicationEvent(ApplicationEvent event) )
import org.springframework.context.ApplicationEvent;
public class EmailEvent extends <strong style="background-color: rgb(102, 255, 153);">ApplicationEvent</strong> {
private static final long serialVersionUID = 1L;
private String address;
private String text;
public EmailEvent(Object source) {
super(source);
}
public EmailEvent(Object source,String address,String text){
super(source);
this.setAddress(address);
this.setText(text);
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
public class EmailNotifier <strong style="background-color: rgb(102, 255, 153);">implements ApplicationListener</strong> {
// 该方法会在容器发生事件时自动触发
@Override
public void <span style="background-color: rgb(153, 255, 255);"><strong>onApplicationEvent</strong></span>(ApplicationEvent event) {
if (event instanceof EmailEvent) {
// 只处理EmailEvent,发送email通知。。。。
EmailEvent emailEvent = (EmailEvent) event;
System.out.println("需要发送邮件的接收地址 " + emailEvent.getAddress());
System.out.println("需要发送邮件的邮件正文" + emailEvent.getText());
} else {
// 容器内置事件不作任何处理
System.out.println("容器本身的事件: " + event);
}
}
}
bean.xml
<strong style="background-color: rgb(51, 255, 255);"><!-- 配置监听器 -->
<bean class="com.cnpc.spring.listener.EmailNotifier"/></strong>
@Test
// ApplicationContext的事件机制
public void testEvent() { // 需要aop
ApplicationContext context = new ClassPathXmlApplicationContext(
new String[] { "bean.xml" });
EmailEvent event = new EmailEvent("", "aups@163.com",
"this is a test email");
// 主动触发容器事件
<span style="background-color: rgb(51, 255, 255);"><strong>context.publishEvent(event);</strong></span>
}
容器本身的事件: org.springframework.context.event.ContextRefreshedEvent[source=org.springframework.context.support.ClassPathXmlApplicationContext@73844508: startup date [Tue Feb 03 13:31:17 CST 2015]; root of context hierarchy]
需要发送邮件的接收地址 apus@163.com
需要发送邮件的邮件正文this is a test email.
监听器不仅监听到程序所触发的事件,也监听到容器内置的事件。实际上,如果开发者需要在Spring容器初始化,销毁时回调自定义方法,就可以通过上面的事件监听器来实现。