MailSendEvent.java
import org.springframework.context.ApplicationContext;
import org.springframework.context.event.ApplicationContextEvent;
public class MailSendEvent extends ApplicationContextEvent {
private String to;
public MailSendEvent(ApplicationContext source, String to) {
super(source);
this.to = to;
}
public String getTo() {
return this.to;
}
}
MailSendListener.java
import org.springframework.context.ApplicationListener;
public class MailSendListener implements ApplicationListener<MailSendEvent>{
public void onApplicationEvent(MailSendEvent event) {
MailSendEvent mse = (MailSendEvent) event;
System.out.println("MailSendListener:向" + mse.getTo() + "发送完一封邮件");
}
}
MailSender.java
public class MailSender implements ApplicationContextAware {
private ApplicationContext ctx ;
public void setApplicationContext(ApplicationContext ctx)
throws BeansException {
this.ctx = ctx;
}
public void sendMail(String to){
System.out.println("MailSender:模拟发送邮件...");
MailSendEvent mse = new MailSendEvent(this.ctx,to);
ctx.publishEvent(mse);
}
}
beans.xml
<?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.0.xsd">
<bean class="com.baobaotao.event.MailSendListener"/>
<bean id="mailSender" class="com.baobaotao.event.MailSender"/>
</beans>
ApplicationEventTest.java
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ApplicatonEventTest {
public static void main(String[] args) {
String resourceFile = "com/baobaotao/event/beans.xml";
ApplicationContext ctx = new ClassPathXmlApplicationContext(resourceFile);
MailSender mailSender = ctx.getBean(MailSender.class);
mailSender.sendMail("test mail.");
System.out.println("done.");
}
}
首先由sendMail方法产生一个MailSendEvent , 并把这个事件发送给所有事件监听器。
MailSendListener类继承了事件监听器接口ApplicationListener,处理了这个事件。
其中
public void onApplicationEvent(MailSendEvent event) {
MailSendEvent mse = (MailSendEvent) event;
System.out.println("MailSendListener:向" + mse.getTo() + "发送完一封邮件");
}
这个方法就是处理事件的方法。
Spring只有两个事件监听器接口
1.ApplicaionListener , 只有一个方法
onApplicationEvent(E event) , 该方法接受ApplicationEvent 事件对象,在该方法中编写事件的响应处理逻辑。
2.SmartApplicationListener接口,有两个方法:
1)boolean supportsEventType(Class<? extends ApplicationEvent>eventType) : 指定监听器支持哪种类型的容器事件,即他只会对该类型的事件做出响应。
2)boolean supportsSourceType(Class<?> sourceType) : 该方法指定监听器仅对何种事件源对象做出响应。