转载自:https://blog.csdn.net/zjw10wei321/article/details/40145241
场景引入:
在web项目中 凡是使用spring都需要在web.xml中配置如下内容:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class> org.springframework.web.context.ContextLoaderListener </listener-class>
</listener>
ContextLoderListener分析:
ContextLoaderListener实现了ServletContextListener接口,ServletContextListener是Java EE标准接口之一,tomcat等容器启动时便会触发该接口的contextInitialized。
调用堆栈如下:
从图中可以看出:
java容器启动触发ContextLoaderListener.contextInitialized
contextInitialized 方法调用ContextLoader.initWebApplicationContext方法。
那么initWebApplicationContext中做了那些事情呢?
1.从servlet上下文中获取contextConfigLocation
2.判断servlet上下文中是否配置contextClass,未配置默认创建XmlWebApplicationContext(这里并没有硬编码,而是使用了策略模式,在类的静态代码块读取ContextLoader.property,内容如下)
org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext
3.配置并且刷新XmlWebApplicationContext
3.1 初始化XmlWebApplicationContext中的Environment的配置
3.2 refresh容器
4.将XmlWebApplicationContext保存到servletContext中