容器(tomcat)在启动时会读取web.xml中listener
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
说白了就是一个ServletContextListener所以在容器(tomcat)启动的Listener会被初始化,并且执行contextInitized(ServletEvent event)方法,所以主要看如下两个部分代码:
- 初始化ServletContextListener
contextInitialized(ServletContextEvent even)执行
初始化ServletContextListener所以如下静态代码块会被执行
Properties defaultStrategies = null;
static {
try {
ClassPathResource ex = new ClassPathResource("ContextLoader.properties", ContextLoader.class);
defaultStrategies = PropertiesLoaderUtils.loadProperties(ex);
} catch (IOException var1) {
throw new IllegalStateException("Could not load \'ContextLoader.properties\': " + var1.getMessage());
}
currentContextPerThread = new ConcurrentHashMap(1);
}
看到没有就是读取ContextLoader.properties的配置文件文件中就一行配置key=value如下所示:
org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext
public void contextInitialized(ServletContextEvent event) { this.initWebApplicationContext(event.getServletContext());
}
注意:ContextLoaderListener的父类ContextLoader就是这里的上面代码的this
即ContextLoader.initWebApplicationContext(ServletContext)
该方法主要做了如下几个事情:
//读取ContextLoader.properties获取XmlWebApplicationContext
//通过反射获取webApplicationContext实例
this.context = this.createWebApplicationContext(servletContext);
//加载配置文件(最关键的、最复杂部分)
this.configureAndRefreshWebApplicationContext(err, servletContext);
//将WebApplicationContext放入到ServletContext中
servletContext.setAttribute("org.springframework.web.context.WebApplicationContext.ROOT", this.context);
protected WebApplicationContext createWebApplicationContext(ServletContext sc) {
//为了方便读者查看将部分代码的实现直接写到这里了
//读取配置文件
contextClassName = defaultStrategies.getProperty(WebApplicationContext.class.getName());
//获取WebApplicationContext实例
return (ConfigurableWebApplicationContext)BeanUtils.instantiateClass(contextClass);
}
总结:
第一步:读取Spring自己的默认配置
ContextLoader.properties,获取WebApplicatiotContext实例
①、tomcat启动读取web.xml的Listener
②、ContextLoader的静态代码块读取ContextLoader.properties文件获取XmlWebApplicationContext
③、从②读取配置得到xmlWebApplicatoinContext
通过反射获取WebApplicationContext对象
第二步:
读取我们程序员指定的配置文件,比较复杂放到下一篇博文
第三步:
将WebApplicationContext放入到ServletContext中