Spring 使用的设计模式(二) Observer(观察者)
?? 由上代码可知,AbstractApplicationContext类并没有具体的做事件广播,而是委托给ApplicationEventMulticaster来进行,ApplicationEventMulticaster的multicastEvent()方法实现如下:
?spring先从beanFactory中获取ApplicationEventMulticaster,如果没有自定义,则创建一个SimpleApplicationEventMulticaster?
?
ApplicationEventMulticaster包含以下属性:defaultRetriever即为注册表,注册监听事件的相关消息,retrieverCache用来做defaultRetriever的缓存
?
?ApplicationEventMulticaster的方法multicastEvent()为:?
?
public class TestDemo {private ApplicationContext context;private MessageSource resources;@Beforepublic void before() {context = new FileSystemXmlApplicationContext("WebRoot/WEB-INF/spring/spring.xml");}public static void main(String[] args) {}@Testpublic void testA() {context.publishEvent(new DIYEvent("test data!"));}@Afterpublic void after() {}}?获取ApplicationContext,发布事件
?
调试结果:test data!