springmvcContextLoaderListener详解

12次阅读

共计 1817 个字符,预计需要花费 5 分钟才能阅读完成。

<!-- 配置 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());
    }
}
  1. ContextLoaderListener 实现了 ServletContextListener, ServletContextListener 接口会在 tomcat 容器启动时调用其 contextInitialized() 方法
  2. 进入 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;
        }
    }

正文完
 0