public WebApplicationContext initWebApplicationContext(ServletContext servletContext){ if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) { thrownew 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); //下面这个日志就是我们经常在启动Spring项目时看到的日志信息: //Initializing Spring root WebApplicationContext //Root WebApplicationContext: initialization started 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. //如果当前容器为null,则创建一个容器,并将servletContext上下文作为参数传递进去, if (this.context == null) { this.context = createWebApplicationContext(servletContext); } //判断当前容器是否为可配置的,只有是Configurable的容器,才能进行后续的配置 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 大专栏Spring源码系列:Spring的启动过程 · glmapperif (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); } //三步走中的第二步:配置并且刷新当前容器 configureAndRefreshWebApplicationContext(cwac, servletContext); } } //将配置并且刷新过的容器存入servlet上下文中,并以WebApplicationContext的类名作为key值