if (this.logger.isInfoEnabled()) { long elapsedTime = System.currentTimeMillis() - startTime; this.logger.info("FrameworkServlet '" + getServletName() + "': initialization completed in " + elapsedTime + " ms"); } }
initWebApplicationContext方法主要代码如下图所示。
/** * 方法位置:FrameworkServlet#initServletBean() */ protected WebApplicationContext initWebApplicationContext(){ //在getServletContext 中查找WebApplicationContext,如果web.xml配置了contextLoaderListener //和contetConfigLocation则rootContext 是由xml配置了contextLoaderListener 监听的上下文 WebApplicationContext rootContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); WebApplicationContext wac = null; //DispatcherServlet的构造方法有一个是由WebApplicationContext进行创建的构造方法,如果使用这种 //方式,则由下面的代码生成实例 if (this.webApplicationContext != null) { // A context instance was injected at construction time -> use it wac = this.webApplicationContext; if (wac instanceof ConfigurableWebApplicationContext) { ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac; 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 -> set // the root application context (if any; may be null) as the parent cwac.setParent(rootContext); } configureAndRefreshWebApplicationContext(cwac); } } } if (wac == null) { // 如果执行到这里wac还是为空,再次到ServletContext中查找,没有报错 wac = findWebApplicationContext(); } if (wac == null) { // 如果还是为空,就创建一个局部变量 wac = createWebApplicationContext(rootContext); }
if (!this.refreshEventReceived) { //这里手动刷新,交给子类实现 onRefresh(wac); }
if (this.publishContext) { // 将这里的WebApplicationContext 放入 servletContext String attrName = getServletContextAttributeName(); getServletContext().setAttribute(attrName, wac); if (this.logger.isDebugEnabled()) { this.logger.debug("Published WebApplicationContext of servlet '" + getServletName() + "' as ServletContext attribute with name [" + attrName + "]"); } }
/** * Initialize the strategy objects that this servlet uses. * <p>May be overridden in subclasses in order to initialize further strategy objects. */ protectedvoidinitStrategies(ApplicationContext context){ initMultipartResolver(context); initLocaleResolver(context); initThemeResolver(context); initHandlerMappings(context); initHandlerAdapters(context); initHandlerExceptionResolvers(context); initRequestToViewNameTranslator(context); initViewResolvers(context); initFlashMapManager(context); }