spring專案啟動完成後,自動執行一次指定方法
阿新 • • 發佈:2018-12-27
背景
因為需要保證所有排程相關的依賴注入spring容器才建立所以定時排程任務,所以需要實現在Spring容器將所有的Bean都初始化完成之後才自動執行一次執行方法(建立一個排程任務)
實現
實現ApplicationListener介面,並實現 onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent)方法
@Service
public class SearchReceive implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
if (contextRefreshedEvent.getApplicationContext().getParent().getParent() == null) {//保證只執行一次
//需要執行的方法
}
}
}
至於為什麼先做判斷,因為Spring存在兩個容器,一個是root application context ,另一個就是我們自己的 projectName-servlet context(作為root application context的子容器)。這種情況下,就會造成onApplicationEvent方法被執行兩次。為了避免上面提到的問題,我們可以只在root application context初始化完成後呼叫邏輯程式碼,其他的容器的初始化完成,則不做任何處理