1.作用
要在web应用中使用spring来管理实例以及使用spring的其他功能,就需要在web应用容器初始化的时候创建一个ApplicationContext。这时想到使用context监听器了,这样可以在web应用创建的时候也实例化一个ApplicationContext,用来在整个应用中使用
2.分析
(1)在web.xml中配置的是ContextLoaderListener
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<!--contextConfigLocation在 ContextLoaderListener类中的默认值是 /WEB-INF/applicationContext.xml-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
<!-- <param-value>classpath:applicationContext*.xml</param-value> -->
</context-param>
(2)看一下ContextLoaderListener
public class ContextLoaderListener extends ContextLoader implements ServletContextListener {
private ContextLoader contextLoader;
/**
* Initialize the root web application context.
*/
public void contextInitialized(ServletContextEvent event) {
this.contextLoader = createContextLoader();
if (this.contextLoader == null) {
this.contextLoader = this;
}
this.contextLoader.initWebApplicationContext(event.getServletContext());
}
......
}
实现了ServletContextListener,所以就能在web应用启动的时候初始化spring
(3)看其中的initWebApplicationContext方法
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
..........
try {
........
this.context = createWebApplicationContext(servletContext, parent);
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
......
return this.context;
}
......
}
去除多余代码之后,核心就是如上。
可以看出就是创建一个WebApplicationContext,然后放到servletContext中
(3)看WebApplicationContext中的createWebApplicationContext方法
protected WebApplicationContext createWebApplicationContext(ServletContext sc, ApplicationContext parent) {
Class<?> contextClass = determineContextClass(sc);
.........
ConfigurableWebApplicationContext wac =
(ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
.....
wac.setParent(parent);
wac.setServletContext(sc);
wac.setConfigLocation(sc.getInitParameter(CONFIG_LOCATION_PARAM));
customizeContext(sc, wac);
wac.refresh();
return wac;
}
实际上就是通过反射生成一个WebApplicationContext
(4)注意
默认情况下,spring会使用XMLWebApplicationContext,在这个context中
public class XmlWebApplicationContext extends AbstractRefreshableWebApplicationContext {
/** Default config location for the root context */
public static final String DEFAULT_CONFIG_LOCATION = "/WEB-INF/applicationContext.xml";
/** Default prefix for building a config location for a namespace */
public static final String DEFAULT_CONFIG_LOCATION_PREFIX = "/WEB-INF/";
/** Default suffix for building a config location for a namespace */
public static final String DEFAULT_CONFIG_LOCATION_SUFFIX = ".xml";
这也就看出来,如果没有指定config location的话,会默认从WEB-INF/applicationContext.xml中读取配置文件