1. 程式人生 > >spring(二十九)--web服務啟動spring自動執行ApplicationListener的用法

spring(二十九)--web服務啟動spring自動執行ApplicationListener的用法

來自:https://www.cnblogs.com/xxj-bigshow/p/7244822.html

我們知道,一般來說一個專案啟動時需要載入或者執行一些特殊的任務來初始化系統,通常的做法就是用servlet去初始化,但是servlet在使用spring bean時不能直接注入,還需要在web.xml配置,比較麻煩。今天介紹一下使用spring啟動初始化的方法。其實很簡單,只需兩步就可以了。

在開發時有時候需要在整個應用開始執行時執行一些特定程式碼,比如初始化環境,準備測試資料、載入一些資料到記憶體等等。

spring中可以通過ApplicationListener來實現相關的功能,載入完成後觸發contextrefreshedevent事件(上下檔案重新整理事件)

但是這個時候,會存在一個問題,在web 專案中(spring mvc),系統會存在兩個容器,一個是root application context ,另一個就是我們自己的 projectName-servlet  context(作為root application context的子容器)。

這種情況下,就會造成onApplicationEvent方法被執行兩次。為了避免上面提到的問題,我們可以只在root application context初始化完成後呼叫邏輯程式碼,其他的容器的初始化完成,則不做任何處理,修改後程式碼

  1. 實現ApplicationListener介面:
public class Init implements ApplicationListener<ContextRefreshedEvent>{

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {

        if(event.getApplicationContext().getParent() == null){//root application context 沒有parent
            //TODO 這裡寫下將要初始化的內容

        }
    }

}

 2. 在spring applicationContex.xml中配置該bean

 <bean id="cmsApplicationListener" class="com.xx.xxx.Init"/>

這樣服務啟動時,就會自動載入並執行了。

後續發現加上以上判斷還是能執行兩次,不加的話三次,最終研究結果使用以下判斷更加準確:event.getApplicationContext().getDisplayName().equals("Root WebApplicationContext")