[springmvc]ContextLoaderListener详解



    org.springframework.web.context.ContextLoaderListener


    
    contextConfigLocation
    classpath:applicationContext.xml

标签中,ContextLoaderListener是用来创建Spring容器的; 标签则指定了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;
        }
    }

你可能感兴趣的:(spring-mvc,spring,java)