ContextLoaderListener的作用

1. 概述

在web應(yīng)用啟動的,ContextLoaderListener讀取contextConfigLocation中定義的xml文件,自動裝配ApplicationContext的配置信息,并產(chǎn)生WebApplicationContext對象,然后將這個對象放置在ServletContext的屬性里,這樣我們就可以在servlet里得到WebApplicationContext對象。

2. 源碼分析

  • ContextLoaderListener繼承關(guān)系
public class ContextLoaderListener extends ContextLoader implements ServletContextListener{ 
...
}

ContextLoader: 可以指定Web應(yīng)用程序啟動時(shí),載入IOC容器的配置文件地址;
ServletContextListener:接口里的函數(shù),會結(jié)合Web容器的生命周期被調(diào)用;ServletContextListener是ServletContext的監(jiān)聽者。

在服務(wù)器啟動時(shí),由于ServletContext加載,contextInitialized方法會被調(diào)用,進(jìn)而初始化WebApplicationContext。

@Override
    public void contextInitialized(ServletContextEvent event) {
        initWebApplicationContext(event.getServletContext());
    }

initWebApplicationContext()負(fù)責(zé)創(chuàng)建IOC容器

public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
    ...
    //初始化容器
    configureAndRefreshWebApplicationContext(cwac, servletContext);
    ...
}
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {
  ...
  //調(diào)用refresh方法,初始化容器
  wac.refresh();
  ...
}

需要注意: ServletContextListener是web組件,真正實(shí)例化它的是tomcat;ContextLoader是spring容器的組件,用來初始化容器。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容