Spring
中提供一些Aware相关的接口,BeanFactoryAware、 ApplicationContextAware、ResourceLoaderAware、ServletContextAware等等,其中最常用到的是ApplicationContextAware。实现ApplicationContextAware的Bean,在Bean被初始后,将会被注入 ApplicationContext的实例。ApplicationContextAware
提供了publishEvent()方法,实现Observer(观察者)设计模式的事件传播机
,提供了针对Bean的事件传播功能。通过Application.publishEvent方法,我们可以将事件通知系统内所有的ApplicationListener。
Spring事件处理一般过程:
定义Event类,继承org.springframework.context.ApplicationEvent.
编写发布事件类Publisher,实现org.springframework.context.ApplicationContextAware接口.
覆盖方法
setApplicationContext ( ApplicationContext applicationContext )和发布方法
publish(Object obj)
定义时间监听类
EventListener,实现
ApplicationListener接口,实现方法
onApplicationEvent ( ApplicationEvent event ).
1 public class MessageEvent extends
ApplicationEvent {
2 /**
3
*
4 */
5 private static final long serialVersionUID = 1L
;
6 private
String msg;
7 public
MessageEvent(Object source, String msg) {
8 super
(source);
9 this.msg =
msg;
10
}
11
12 public
String getMessage() {
13 return
msg;
14
}
15
}
1
public class Publisher implements
ApplicationContextAware {
2
3 private
ApplicationContext ctx;
4
5 public void
setApplicationContext(ApplicationContext applicationContext)
6 throws
BeansException {
7 this.ctx =
applicationContext;
8
9
}
10
11 public void
publish(String message) {
12 ctx.publishEvent(new MessageEvent(this
, message));
13
}
14
15 public static void
main(String[] args) {
16 ApplicationContext ctx = new
FileSystemXmlApplicationContext(
17 "src/applicationContext.xml"
);
18
19 Publisher pub = (Publisher) ctx.getBean("publisher"
);
20 pub.publish("Hello World!"
);
21 pub.publish("The quick brown fox jumped over the lazy dog"
);
22
}
23
24 }
1 public class MessageEventListener implements
ApplicationListener {
2
3 public void
onApplicationEvent(ApplicationEvent event) {
4 if(event instanceof
MessageEvent) {
5 MessageEvent msgEvt =
(MessageEvent)event;
6 System.out.println("Received: " +
msgEvt.getMessage());
7
}
8
}
9 }
1 <beans>
2 <bean id="publisher" class="Publisher"/>
3 <bean id="messageEventListener" class="MessageEventListener"/>
4 </beans>
在运行期,ApplicationContext会自动在当前的所有Bean中寻找ApplicationListener接口的实现,并将其作为事件接收对象。当Application.publishEvent方法调用时,所有的ApplicationListener接口实现都会被激发,每个ApplicationListener可根据事件的类型判断是否是自己需要处理的事件,如上面的ActionListener只处理ActionEvent事件。
凤凰涅槃/浴火重生/马不停蹄/只争朝夕
隐姓埋名/低调华丽/简单生活/完美人生