<!-- 配置Listener, 用来创建spring容器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<!-- 配置Listener参数:告诉它Spring的配置文件位置,它好去创建容器 -->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listenter>标签中,ContextLoaderListener是用来创建Spring容器的; <context-param>标签则指定了Spring配置文件的位置
为什么ContextLoaderListener能创建Spring容器呢, 来看一下部分源码
public class ContextLoaderListener extends ContextLoader implements ServletContextListener {
/**
* Initialize the root web application context.
*/
@Override
public void contextInitialized(ServletContextEvent event) {
initWebApplicationContext(event.getServletContext());
}
}
- ContextLoaderListener实现了ServletContextListener, ServletContextListener接口会在tomcat容器启动时调用其contextInitialized()方法
- 进入initWebApplicationContext()方法内部, 注入一个servletContext对象, 同时返回WebApplicationContext容器对象, 部分代码如下:
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
Log logger = LogFactory.getLog(ContextLoader.class);
servletContext.log("Initializing Spring root WebApplicationContext");
if (logger.isInfoEnabled()) {
logger.info("Root WebApplicationContext: initialization started");
}
long startTime = System.currentTimeMillis();
try {
if (this.context == null) {
this.context = createWebApplicationContext(servletContext);
}
if (this.context instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
if (!cwac.isActive()) {
/** 此处省略部分代码 */
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;
}
return this.context;
}
}