Spring項目啓動自動執行一次指定方法

Spring項目啓動自動執行一次指定方法

   點關注不迷路,歡迎再訪!		

實現ApplicationListener接口,並實現 onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent)方法

springmvc:

@Service
public class SearchReceive implements  ApplicationListener<ContextRefreshedEvent> {
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        if (contextRefreshedEvent.getApplicationContext().getParent() == null) {//保證只執行一次
            //需要執行的方法
        }
    }
}

爲什麼先做判斷?

Spring存在兩個容器:一個是root application context ,另一個就是我們自己的 projectName-servlet context(作爲root application context的子容器)。這種情況下,就會造成onApplicationEvent方法被執行兩次。爲了避免上面提到的問題,我們可以只在root application context初始化完成後調用邏輯代碼,其他的容器的初始化完成,則不做任何處理。

發佈了108 篇原創文章 · 獲贊 38 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章