ContextLoader启动后的操作
在文章Spring源码解析(I) 基于SSM看Spring的使用和Spring启动监听中,讲述了web容器启动后会触发的方法实现中生成Context的部分,回顾下核心方法:
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) { 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. //如果非空 是针对Servlet 3.1+自定义Context的情况 if (this.context == null) { //创建一个ApplicationContext this.context = createWebApplicationContext(servletContext); } // 0. 对于默认的XmlWebApplicationContext 肯定会进入这一分支 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); } //在此处会加载具体的配置项,例如contextConfigLocation configureAndRefreshWebApplicationContext(cwac, servletContext); } } 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; } }
我们已经分析到了0.处,他对我们生成的容器做了一个判断,对于web.xml监听初始化的Context,其生成的WebApplicationContext都是ConfigurableWebApplicationContext的子类,所以必然会进入if分支。
首先通过loadParentContext先加载了父容器,默认是null。然后调用了configureAndRefreshWebApplicationContext方法进行初始化和配置项的读取。
这回我们知道启动日志中的如下两行是哪来的了(是使用了Springboot的日志所以开始前输出略微不同):
web.xml配置文件读取:
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 String idParam = sc.getInitParameter(CONTEXT_ID_PARAM); if (idParam != null) { wac.setId(idParam); } else { // Generate default id... wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX + //WebApplicationContext.class.getName() + ":"; ObjectUtils.getDisplayString(sc.getContextPath())); } } wac.setServletContext(sc); //读取web.xml的配置参数 // <init-param> // <param-name>contextConfigLocation</param-name> // <param-value>classpath:spring/spring-*.xml</param-value> // </init-param> String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM); //contextConfigLocation if (configLocationParam != null) { wac.setConfigLocation(configLocationParam); } //初始化environment,主要是处理配置中的占位符属性资源,这样一些InitParam也能读取到了 // 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 ConfigurableEnvironment env = wac.getEnvironment(); if (env instanceof ConfigurableWebEnvironment) { ((ConfigurableWebEnvironment) env).initPropertySources(sc, null); } //refresh之前的回调,会实例化继承了ApplicationContextInitializer的类 customizeContext(sc, wac); //refresh()是真正加载beans的地方,是Spring的核心方法 wac.refresh(); }
ApplicationContextInitializer——refresh前的回调
在如上调用refresh之前,先调用了customizeContext方法,此方法是refresh之前的回调方法,负责初始化一些继承了ApplicationContextInitializer类,实例化并调用其initialize方法,例如我们定义了一个类继承于ApplicationContextInitializer:
public class MyApplicationContextInitializer implements ApplicationContextInitializer { @Override public void initialize(ConfigurableApplicationContext configurableApplicationContext) { System.out.println("----- initialize -----") String beans[] = configurableApplicationContext.getBeanDefinitionNames(); for(String bean:beans){ System.out.println("[bean]: "+ bean); } } }
然后在web.xml中将其注册(多个用逗号分割,从左向右加载):
<context-param> <param-name>contextInitializerClasses</param-name> <param-value>com.xxx.MyApplicationContextInitializer</param-value> </context-param>
这样在程序启动时,我们便能在“Root WebApplicationContext initialized in xxx ms ”的日志之前看到这样的日志: