实现了ApplicationListener接口的bean,每当一个ApplicationEvent发布到ApplicationContext时,该Listener bean将得到通知。这是标准的观察者模式
示例:
import org.springframework.context.ApplicationEvent;
public class MyEvent extends ApplicationEvent {
private static final long serialVersionUID = -155227031531674679L;
private String msg;
public MyEvent(String msg) {
super(msg);
this.msg = msg;
}
public void myevent() {
System.out.println("轮到我了");
System.out.println(msg);
System.out.println("结束了");
}
}
import org.springframework.context.ApplicationEvent;
public class MyEvent2 extends ApplicationEvent {
private static final long serialVersionUID = -1077732602632408750L;
private String msg;
public MyEvent2(String msg) {
super(msg);
this.msg = msg;
}
public void myevent() {
System.out.println("轮到我了2");
System.out.println(msg);
System.out.println("结束了2");
}
}
监听器:
import org.springframework.context.ApplicationListener;
public class MyListener implements ApplicationListener<MyEvent> {
@Override
public void onApplicationEvent(MyEvent event) {
// TODO Auto-generated method stub
event.myevent();
}
}
import org.springframework.context.ApplicationListener;
public class MyListener2 implements ApplicationListener<MyEvent2> {
@Override
public void onApplicationEvent(MyEvent2 event) {
// TODO Auto-generated method stub
event.myevent();
}
}
配置文件:
<?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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="myListener" class="com.learn1.listener.listener.MyListener" />
<bean id="myListener2" class="com.learn1.listener.listener.MyListener2" />
</beans>
测试类:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyAction {
public static void main(String[] args) {
@SuppressWarnings("resource")
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext2.xml");
MyEvent event = new MyEvent("event");
MyEvent2 event2 = new MyEvent2("event2");
MyEvent event3 = new MyEvent("event3");
context.publishEvent(event);
context.publishEvent(event2);
context.publishEvent(event3);
}
}
结果:
轮到我了
event
结束了
轮到我了2
event2
结束了2
轮到我了
event3
结束了