一 配置
<?xml version="1.0" encoding="GBK"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<!-- 配置监听器 -->
<bean class="org.crazyit.app.listener.EmailNotifier"/>
</beans>
二 事件
package org.crazyit.app.event;
import org.springframework.context.ApplicationEvent;
public class EmailEvent extends ApplicationEvent
{
private String address;
private String text;
public EmailEvent(Object source)
{
super(source);
}
// 初始化全部成员变量的构造器
public EmailEvent(Object source , String address , String text)
{
super(source);
this.address = address;
this.text = text;
}
// address的setter和getter方法
public void setAddress(String address)
{
this.address = address;
}
public String getAddress()
{
return this.address;
}
// text的setter和getter方法
public void setText(String text)
{
this.text = text;
}
public String getText()
{
return this.text;
}
}
三 监听器
package org.crazyit.app.listener;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ApplicationEvent;
import org.crazyit.app.event.*;
public class EmailNotifier implements ApplicationListener
{
// 该方法会在容器发生事件时自动触发
public void onApplicationEvent(ApplicationEvent evt)
{
// 只处理EmailEvent,模拟发送email通知...
if (evt instanceof EmailEvent)
{
EmailEvent emailEvent = (EmailEvent)evt;
System.out.println("需要发送邮件的接收地址 "
+ emailEvent.getAddress());
System.out.println("需要发送邮件的邮件正文 "
+ emailEvent.getText());
}
else
{
// 其他事件不作任何处理
System.out.println("其他事件:" + evt);
}
}
}
四 测试类
package lee;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.crazyit.app.event.*;
public class SpringTest
{
public static void main(String[] args)
{
ApplicationContext ctx = new
ClassPathXmlApplicationContext("beans.xml");
// 创建一个ApplicationEvent对象
EmailEvent ele = new EmailEvent("test" ,
"spring_test@163.com" , "this is a test");
// 发布容器事件
ctx.publishEvent(ele);
}
}
五 测试
其他事件:org.springframework.context.event.ContextRefreshedEvent[source=org.springframework.context.support.ClassPathXmlApplicationContext@21b8d17c: startup date [Thu Sep 19 20:12:54 CST 2019]; root of context hierarchy]
需要发送邮件的接收地址 spring_test@163.com
需要发送邮件的邮件正文 this is a test