借鑑業餘草中作者 herman的文章,結合我自己的項目,發表一下觀點,不合理的地方請各位讀者多多指教。
轉載地址:https://www.xttblog.com/?p=2053
ApplicationListener和ContextRefreshedEvent一般都是成對出現的。
事件機制作爲一種編程機制,在許多語言中都提供了支持。JAVA語言也不例外,java中的事件機制的參與者有3種角色:
- event object
- event source
- event listener
這三個角色的含義字面上很好解,它們就定義了事件機制的一個基本模型。作爲一種常用的編程設計機制,許多開源框架的設計中都使用了事件機制。SpringFramework也不例外。
在IOC的容器的啓動過程,當所有的bean都已經處理完成之後,spring ioc容器會有一個發佈事件的動作。從 AbstractApplicationContext 的源碼中就可以看出:
1 2 3 4 5 6 7 8 9 10 11 | protected void finishRefresh() { // Initialize lifecycle processor for this context. initLifecycleProcessor(); // Propagate refresh to lifecycle processor first. getLifecycleProcessor().onRefresh(); // Publish the final event. publishEvent( new ContextRefreshedEvent( this )); // 業餘草:www.xttblog.com // Participate in LiveBeansView MBean, if active. LiveBeansView.registerApplicationContext( this ); } |
這樣,當ioc容器加載處理完相應的bean之後,也給我們提供了一個機會(先有InitializingBean,後有ApplicationListener<ContextRefreshedEvent>),可以去做一些自己想做的事。其實這也就是spring ioc容器給提供的一個擴展的地方。我們可以這樣使用這個擴展機制。
1 2 | org.springframework.context.ApplicationEvent org.springframework.context.ApplicationListener |
一個最簡單的方式就是,讓我們的bean實現ApplicationListener接口,這樣當發佈事件時,spring的ioc容器就會以容器的實例對象作爲事件源類,並從中找到事件的監聽者,此時ApplicationListener接口實例中的onApplicationEvent(E event)方法就會被調用,我們的邏輯代碼就會寫在此處。這樣我們的目的就達到了。但這也帶來一個思考,有人可能會想,這樣的代碼我們也可以通過實現spring的InitializingBean接口來實現啊,也會被spring容器去自動調用,但是大家應該想到,如果我們現在想做的事,是必須要等到所有的bean都被處理完成之後再進行,此時InitializingBean接口的實現就不合適了,所以需要深刻理解事件機制的應用場合。
曾經有一位同事利用 ApplicationListener,重複加載了好幾次 xml 配置文件。所以基礎知識一定要掌握。
下面是一個完整的例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | public class ApplicationContextListener implements ApplicationListener<ContextRefreshedEvent> { private static Logger log = LoggerFactory.getLogger (ApplicationContextListener. class ); @Override public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent){ // root application context if ( null == contextRefreshedEvent.getApplicationContext().getParent()) { log.debug( ">>>>> spring初始化完畢 <<<<<" ); // spring初始化完畢後,通過反射調用所有使用BaseService註解的initMapper方法 Map<String, Object> baseServices = contextRefreshedEvent.getApplicationContext(). getBeansWithAnnotation(BaseService. class ); for (Object service : baseServices.values()) { log.debug( ">>>>> {}.initMapper()" , service.getClass().getName()); try { Method initMapper = service.getClass().getMethod( "initMapper" ); initMapper.invoke(service); } catch (Exception e) { log.error( "初始化BaseService的initMapper方法異常" , e); e.printStackTrace(); } } // 系統入口初始化,業餘草:www.xttblog.com Map<String, BaseInterface> baseInterfaceBeans = contextRefreshedEvent.getApplicationContext(). getBeansOfType(BaseInterface. class ); for (Object service : baseInterfaceBeans.values()) { _log.debug( ">>>>> {}.init()" , service.getClass().getName()); try { Method init = service.getClass().getMethod( "init" ); init.invoke(service); } catch (Exception e) { _log.error( "初始化BaseInterface的init方法異常" , e); e.printStackTrace(); } } } } } |
所以,我們的重點來了,我們如果要實現的是在所有的bean都被處理完成之後再進行操作,
就需要實現ApplicationListener<ContextRefreshedEvent>接口進行操作,同時,
applicationontext和使用MVC之後的webApplicationontext會兩次調用上面的方法,如何區分這個兩種容器呢?
但是這個時候,會存在一個問題,在web 項目中(spring mvc),系統會存在兩個容器,一個是root application context ,另一個就是我們自己的 projectName-servlet context(作爲root application context的子容器)。
這種情況下,就會造成onApplicationEvent方法被執行兩次。爲了避免上面提到的問題,我們可以只在root application context初始化完成後調用邏輯代碼,其他的容器的初始化完成,則不做任何處理,修改後代碼
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
if(event.getApplicationContext().getParent() == null){//root application context 沒有parent,他就是老大.
//需要執行的邏輯代碼,當spring容器初始化完成後就會執行該方法。
}
}
上面是網上的大部分說法,但是,我在做項目時,我想着爲啥不能進行非null值判斷呢,那樣的話就是projectName-servlet context容器進行管理了,也是可以的呀,後來我一想,原來我的問題實際上是Spring和SpringMVC父子 容器的問題,就看這個想要誰管理你的邏輯代碼,就用哪個容器,非null
判斷是springmvc管理;null值判斷,那裏面的邏輯就是spring管理。這就要求我們必須再看看倆種容器
的區別,在這裏由於版面問題,不再詳述,但是,我會在下一篇文章詳細介紹倆種容器的區別與使用,
下面是我在項目中用到的,我是在springmvc容器管理的,如下:
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
ApplicationContext parentContext = ((ContextRefreshedEvent) event)
.getApplicationContext().getParent();
// 子容器初始化時(spring-mvc)
if (null != parentContext) {
String ctxPath = servletContext.getContextPath();
//讀取全部資源
LinkedHashMap<String, SysResource> AllResourceMap = sysResourceService.getAllResourcesMap();
BeetlUtils.addBeetlSharedVars(Constant.CACHE_ALL_RESOURCE,AllResourceMap);
//初始化任務調度
maintainTaskDefinitionService.initTask();
logger.info("根路徑:"+ctxPath);
logger.info("初始化系統資源:(key:" + Constant.CACHE_ALL_RESOURCE
+ ",value:Map<資源url, SysResource>)");
}
}
目的就是設置beetl共享變量以及初始化任務調度。