spring容器初始化之後執行某些系統初始化動作
最近自己所在的專案中出現此種情形:專案啟動後,需要做一些初始化動作,如,讀取配置檔案、查詢資料庫資料存入快取等。參考前人寫的程式碼的實現方式如下:
思路:編寫一個系統初始化類,該類實現ServletContextListenner介面,並實現contextInitialized(),和contextDestory()方法。
public class SystemInitAfterSpringInited implements ServletContextListenner{
@Override //容器初始化後執行
public void contextInitialized(ServlectContextEvent event){
//通過event 獲取上下文例項
WebApplicationContext application = WebApplicationContextUtils.getWebApplicationContext(event.getServlectContext);
//通過應用上下文例項,獲取由spring容器管理的bean
SomeBean bean1 = (SomeBean) application.getBean("beanName1");
bean1.doSomething();
}
@Override //容器銷燬之前執行
public void contextDestory(ServlectContextEvent event){
//通過event 獲取上下文例項
WebApplicationContext application = WebApplicationContextUtils.getWebApplicationContext(event.getServlectContext);
//通過應用上下文例項,獲取由spring容器管理的bean
SomeBean bean2 = (SomeBean) application.getBean("beanName2");
bean2.doSomething();
}
}