SpringMVC源码(一)ContextLoaderListener

在我们启动 springweb 服务时,spring会初始化ioc容器(WebApplicationContext),装载我们所需要的bean。

具体配看我们的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>

看一下ContextLoaderListener 类,extends ContextLoader implements  ServletContextListener  
父类 ContextLoader可以说是一个工具类,主要用来实现ContextLoaderListener中初始化ioc容器需要的方法。
即ContextLoaderListener 的initWebApplicationContext()方法在其父类中实现;

//初始化方法
	public void contextInitialized(ServletContextEvent event) {
		initWebApplicationContext(event.getServletContext());
	}
//销毁方法
	public void contextDestroyed(ServletContextEvent event) {
		closeWebApplicationContext(event.getServletContext());
		ContextCleanupListener.cleanupAttributes(event.getServletContext());
	}

而实现的 ServletContextListener  类可以说是一个servlet 的监听器,当我们启动tomcat的时候,会默认初始化一些servlet,

当监听到servlet初始化时,ContextLoaderListener便会进行我们的初始化ioc容器。

即servlet 在初始化之后我们的ContextLoaderListener也会进行初始化。

 //servlet/jsp 容器会在应用程序初始化期间调用 contextInitialized()方法。
    public void contextInitialized ( ServletContextEvent sce );
//销毁
    public void contextDestroyed ( ServletContextEvent sce );


我们主要看一下父类ContextLoader中的initWebApplicationContext() 方法,它将我们ioc(WebApplicationContext) 进行

初始化,加载spring文件里面的创建的bean实例,并将它放入到servletcontext当中去。看一下它的具体代码。


public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
		//判断是否创建过容器
		if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {
			throw new IllegalStateException(
					"Cannot initialize context because there is already a root application context present - " +
					"check whether you have multiple ContextLoader* definitions in your web.xml!");
		}


		Log logger = LogFactory.getLog(ContextLoader.class);
		//打印日志 web容器开始初始化
		servletContext.log("Initializing Spring root WebApplicationContext");
		if (logger.isInfoEnabled()) {
			logger.info("Root WebApplicationContext: initialization started");
		}
		long startTime = System.currentTimeMillis();


		try {
			// Store context in local instance variable, to guarantee that
			// it is available on ServletContext shutdown.
			//创建WebApplicationContext
			if (this.context == null) {
				this.context = createWebApplicationContext(servletContext);
			}
			if (this.context instanceof ConfigurableWebApplicationContext) {
				ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
				//判断上下文
				if (!cwac.isActive()) {
					// The context has not yet been refreshed -> provide services such as
					// setting the parent context, setting the application context id, etc
					//是否有父容器
					if (cwac.getParent() == null) {
						// The context instance was injected without an explicit parent ->
						// determine parent for root web application context, if any.
						//获得父容器
						ApplicationContext parent = loadParentContext(servletContext);
						//设置父容器
						cwac.setParent(parent);
					}
					//刷新WebApplicationContext
					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;
			}
			else if (ccl != null) {
				currentContextPerThread.put(ccl, this.context);
			}


			if (logger.isDebugEnabled()) {
				logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" +
						WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]");
			}
			if (logger.isInfoEnabled()) {
				long elapsedTime = System.currentTimeMillis() - startTime;
				logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms");
			}

			//返回这个容器
			return this.context;
		}
		catch (RuntimeException ex) {
			logger.error("Context initialization failed", ex);
			servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
			throw ex;
		}
		catch (Error err) {
			logger.error("Context initialization failed", err);
			servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err);
			throw err;
		}
	}



猜你喜欢

转载自blog.csdn.net/superpojo/article/details/72870005