springboot 啓動時執行代碼,並初始化 servletContext

需求:springboot 啓動後自動執行某些代碼,初始化數據,並將數據放到 servletContext 中。

首先,不可使用 ServletContextListener 即不能用 @WebListener ,因爲 servlet 容器初始化後,spring 並未初始化完畢,不能使用 @Autowired 注入 spring 的對象。

推薦使用 ApplicationListener:啓動項目, spring 加載完畢後,才執行該 ApplicationListener,並且該 Listener 中可以使用 spring 的內容。

@Component
public class SettingDataInitListener implements ApplicationListener<ContextRefreshedEvent> {
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        // 將 ApplicationContext 轉化爲 WebApplicationContext 
        WebApplicationContext webApplicationContext = 
            (WebApplicationContext)contextRefreshedEvent.getApplicationContext();
        // 從 webApplicationContext 中獲取  servletContext 
        ServletContext servletContext = webApplicationContext.getServletContext();
        // servletContext設置值
        servletContext.setAttribute("key", "value");
    }
}

參考:http://www.fengyunxiao.cn

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章