我們平日采用spring 架構 開發項目時,配置檔案web.xml 中總是有這樣一些配置,比如:
<!-- 加載spring配置檔案-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:config/spring-config.xml
classpath:config/spring-cxf.xml
</param-value>
</context-param>
<!-- web啟動監聽配置-->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
而這些配置到底有什麼作用呢?我們從源碼角度分析一下:
1、首先看ContextLoaderListener 類,它繼承ContextLoader 實作 ServletContextListener
public class ContextLoaderListener extends ContextLoader implements ServletContextListener
ContextLoaderListener的作用就是啟動Web容器時,讀取在contextConfigLocation中定義的xml檔案,自動裝配ApplicationContext的配置資訊,并産生WebApplicationContext對象,然後将這個對象放置在ServletContext的屬性裡,這樣我們隻要得到Servlet就可以得到WebApplicationContext對象,并利用這個對象通路spring容器管理的bean。
總之,就是上面這段配置為項目提供了spring支援,初始化了Ioc容器。
ContextLoader 主要作用作為父類指定Web應用程式啟動時載入相應的Ioc容器,完成實際的WebApplicationContext,即Ioc容器的初始化工作在這裡完成,後面會源碼展示。
ServletContextListener 接口繼承EventListener
public interface ServletContextListener extends EventListener
ServletContextListener是ServletContext的監聽者,接口裡的方法會結合Web容器的生命周期被調用,ServletContext發生某些變化,會觸發相應的事件,web伺服器啟動時、ServletContext建立時、web服務關閉時、ServletContext銷毀時等等,都會觸發相應事件,做出預先設計好的相應動作,比如此類中:監聽器的響應動作就是在伺服器啟動時contextInitialized會被調用,關閉的時候contextDestroyed被調用。
/**
* Initialize the root web application context.
啟動時在這裡開始調用,初始化根上下文應用程式
*/
@Override
public void contextInitialized(ServletContextEvent event) {
initWebApplicationContext(event.getServletContext());//點選進入
}
2、進入 ContextLoader 類
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
//如果servletContext對象中存放了spring context,則抛出異常
if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {
throw new IllegalStateException(
"Cannot initialize context because there is already a root application context present - " +
"check whether you have multiple ContextLoader* definitions in your web.xml!");
}
servletContext.log("Initializing Spring root WebApplicationContext");
Log logger = LogFactory.getLog(ContextLoader.class);
if (logger.isInfoEnabled()) {
logger.info("Root WebApplicationContext: initialization started");
}
long startTime = System.currentTimeMillis();
try {
// Store context in local instance variable, to guarantee that
// it is available on ServletContext shutdown.
if (this.context == null) {
//建立WebApplicationContext容器并被強制轉換為ConfigurableWebApplicationContext類型
this.context = createWebApplicationContext(servletContext);
}
if (this.context instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
if (!cwac.isActive()) {
// The context has not yet been refreshed -> provide services such as
// setting the parent context, setting the application context id, etc
if (cwac.getParent() == null) {
// The context instance was injected without an explicit parent ->
// determine parent for root web application context, if any.
//加載父容器
ApplicationContext parent = loadParentContext(servletContext);
cwac.setParent(parent);
}
//加載spring配置檔案,點選進入
configureAndRefreshWebApplicationContext(cwac, servletContext);
}
}//把web容器放到servlet容器中
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
ClassLoader ccl = Thread.currentThread().getContextClassLoader();
if (ccl == ContextLoader.class.getClassLoader()) {
currentContext = this.context;
}
else if (ccl != null) {
currentContextPerThread.put(ccl, this.context);
}
if (logger.isInfoEnabled()) {
long elapsedTime = System.currentTimeMillis() - startTime;
logger.info("Root WebApplicationContext initialized in " + elapsedTime + " ms");
}
return this.context;
}
catch (RuntimeException | Error ex) {
logger.error("Context initialization failed", ex);
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
throw ex;
}
}
來到configureAndRefreshWebApplicationContext方法中
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {
if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
// The application context id is still set to its original default value
// -> assign a more useful id based on available information
//擷取 web.xml 中定義的 contextId 初始化值,未定義
String idParam = sc.getInitParameter(CONTEXT_ID_PARAM);
if (idParam != null) {
wac.setId(idParam);
}
else {
// Generate default id... 設定一個 全局的id
wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
ObjectUtils.getDisplayString(sc.getContextPath()));
}
}
wac.setServletContext(sc);//配置了 servletContext 屬性
//擷取 web.xml 中定義的 contextConfiLocation 初始化參數值 ,已定義
String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);
if (configLocationParam != null) {
wac.setConfigLocation(configLocationParam);
}
// The wac environment's #initPropertySources will be called in any case when the context
// is refreshed; do it eagerly here to ensure servlet property sources are in place for
// use in any post-processing or initialization that occurs below prior to #refresh
//初始化 應用上下文 中 和 Servlet 相關的 占位符 屬性資源
ConfigurableEnvironment env = wac.getEnvironment();
if (env instanceof ConfigurableWebEnvironment) {
((ConfigurableWebEnvironment) env).initPropertySources(sc, null);
}
/// 加載web.xml 中 自定義的 其他初始化内容
customizeContext(sc, wac);
wac.refresh();//WebApplicationContext 的重新整理,核心方法,點選進入後豁然開朗,ctr+t 進入
}
3、進入這個方法,非常熟悉,前面幾篇已經詳細解析過,是spring 源碼的重點方法,這裡就不介紹了。
public abstract class AbstractApplicationContext extends DefaultResourceLoader
implements ConfigurableApplicationContext {
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}
4、重點這是spring 的容器初始化,下篇介紹springMVC 容器初始化;他倆是父子容器關系。敬請期待!