package com.jd.spring.test.event;
import org.springframework.context.ApplicationEvent;
public class EmailEvent extends ApplicationEvent {
private static final long serialVersionUID = 1L;
public String address;
public String text;
public EmailEvent(Object source) {
super(source);
}
public EmailEvent(Object source, String address, String text) {
super(source);
this.address = address;
this.text = text;
}
public void print(){
System.out.println("hello spring event!");
}
}
package com.jd.spring.test.listener;
import com.jd.spring.test.event.EmailEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
public class EmailListener implements ApplicationListener {
public void onApplicationEvent(ApplicationEvent event) {
if(event instanceof EmailEvent){
EmailEvent emailEvent = (EmailEvent)event;
emailEvent.print();
System.out.println("the source is:"+emailEvent.getSource());
System.out.println("the address is:"+emailEvent.address);
System.out.println("the email's context is:"+emailEvent.text);
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- 支持Spring注解 -->
<!--<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />-->
<!-- Annotation -->
<context:annotation-config />
<context:component-scan base-package="com.jd" />
<bean id="emailListener" class="com.jd.spring.test.listener.EmailListener"></bean>
</beans>
package com.jd.spring.test;
import com.jd.spring.test.event.EmailEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
事件传播
ApplicationContext基于Observer模式(java.util包中有对应实现),提供了针对Bean的事件传播功能。
通过Application. publishEvent方法,我们可以将事件通知系统内所有的ApplicationListener。
事件传播的一个典型应用是,当Bean中的操作发生异常(如数据库连接失败),则通过事件传播
机制通知异常监听器进行处理。如一个项目中,就曾经借助事件机制,较好的实现了当系统
异常时在监视终端上报警,同时发送报警SMS至管理员手机的功能。
*/
public class TestApplicationListener {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:beans.xml");
EmailEvent event = new EmailEvent("hello", "boylmx@163.com", "this is a email text!");
context.publishEvent(event);
}
}
打印结果:
hello spring event!
the source is:hello
the address is:boylmx@163.com
the email's context is:this is a email text!