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容器的組件,用來初始化容器。