spring的啟動是建築在servlet容器之上的,所有web工程的初始位置就是web.xml,它配置了servlet的上下文(context)和監聽器(Listener),下面就來看看web.xml里面的配置:
<!--上下文監聽器,用於監聽servlet的啟動過程--> <listener> <description>ServletContextListener</description> <!--這里是自定義監聽器,個性化定制項目啟動提示--> <listener-class>com.trace.app.framework.listeners.ApplicationListener</listener-class> </listener> <!--dispatcherServlet的配置,這個servlet主要用於前端控制,這是springMVC的基礎--> <servlet> <servlet-name>service_dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/services/service_dispatcher-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <!--spring資源上下文定義,在指定地址找到spring的xml配置文件--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/application_context.xml</param-value> </context-param> <!--spring的上下文監聽器--> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <!--Session監聽器,Session作為公共資源存在上下文資源當中,這里也是自定義監聽器--> <listener> <listener-class> com.trace.app.framework.listeners.MySessionListener </listener-class> </listener>
接下來就一點的來解析這樣一個啟動過程。
1. spring的上下文監聽器
代碼如下:
<!--spring資源上下文定義,在指定地址找到spring的xml配置文件--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/application_context.xml</param-value> </context-param> <!--spring的上下文監聽器--> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener>
spring的啟動其實就是IOC容器的啟動過程,通過上述的第一段配置<context-param>
是初始化上下文,然后通過后一段的的<listener>來加載配置文件,其中調用的spring包中的ContextLoaderListener
這個上下文監聽器,ContextLoaderListener
是一個實現了ServletContextListener
接口的監聽器,他的父類是 ContextLoader
,在啟動項目時會觸發contextInitialized
上下文初始化方法。下面我們來看看這個方法:
public void contextInitialized(ServletContextEvent event) { initWebApplicationContext(event.getServletContext()); }
可以看到,這里是調用了父類ContextLoader
的initWebApplicationContext(event.getServletContext());
方法,很顯然,這是對ApplicationContext的初始化方法,也就是到這里正是進入了springIOC的初始化。
接下來再來看看initWebApplicationContext
又做了什么工作,先看看代碼:
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); 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. 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); } 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; }
這個方法還是有點長的,其實仔細看看,出去異常錯誤處理,這個方法主要做了三件事:
- 創建WebApplicationContext。
- 加載對應的spring配置文件中的Bean。
- 將WebApplicationContext放入ServletContext(Java Web的全局變量)中。
上述代碼中createWebApplicationContext(servletContext)
方法即是完成創建WebApplicationContext工作,也就是說這個方法創建了上下文對象,支持用戶自定義上下文對象,但必須繼承ConfigurableWebApplicationContext,而Spring MVC默認使用ConfigurableWebApplicationContext作為ApplicationContext(它僅僅是一個接口)的實現。
再往下走,有一個方法configureAndRefreshWebApplicationContext
就是用來加載spring配置文件中的Bean實例的。這個方法於封裝ApplicationContext數據並且初始化所有相關Bean對象。它會從web.xml中讀取名為 contextConfigLocation的配置,這就是spring xml數據源設置,然后放到ApplicationContext中,最后調用傳說中的refresh
方法執行所有Java對象的創建。
最后完成ApplicationContext創建之后就是將其放入ServletContext中,注意它存儲的key值常量。
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
總結來說如下圖:
2.SpringMVC的啟動過程
web.xml的相關配置:
<!--dispatcherServlet的配置,這個servlet主要用於前端控制,這是springMVC的基礎--> <servlet> <servlet-name>service_dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/services/service_dispatcher-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet>
這里采用這種自定義初始化參數的配置方式,當然也可以使用默認的。這里Spring Web MVC框架將加載“classpath:service_dispatcher-servlet.xml”來進行初始化上下文而不是“/WEB-INF/[servlet名字]-servlet.xml”。
通過上述配置文件很明顯可以看出,springMVC的起始位置是DispatcherServlet(還是spring提供的)
public class DispatcherServlet extends FrameworkServlet { ... ... }
這個類的父類是FrameworkServlet
,FrameworkServlet
又繼承了HttpServletBean
類,HttpServletBean
又繼承了HttpServlet
,HttpServlet
繼承了GenericServlet
。
public abstract class FrameworkServlet extends HttpServletBean implements ApplicationContextAware { ... ... } public abstract class HttpServletBean extends HttpServlet implements EnvironmentCapable, EnvironmentAware { ... ... } public abstract class HttpServlet extends GenericServlet implements java.io.Serializable { ... ... }
所以在這樣一個web容器啟動的時候會調用HttpServletBean
的init方法,這個方法覆蓋了GenericServlet中的init方法。讓我我們來看看代碼:
@Override public final void init() throws ServletException { if (logger.isDebugEnabled()) { logger.debug("Initializing servlet '" + getServletName() + "'"); } // Set bean properties from init parameters. try { PropertyValues pvs = new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties); BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this); ResourceLoader resourceLoader = new ServletContextResourceLoader(getServletContext()); bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, getEnvironment())); initBeanWrapper(bw); bw.setPropertyValues(pvs, true); } catch (BeansException ex) { logger.error("Failed to set bean properties on servlet '" + getServletName() + "'", ex); throw ex; } // Let subclasses do whatever initialization they like. initServletBean(); if (logger.isDebugEnabled()) { logger.debug("Servlet '" + getServletName() + "' configured successfully"); } }
該初始化方法的主要作用:將Servlet初始化參數(init-param)設置到該組件上(如contextAttribute、contextClass、namespace、contextConfigLocation),通過BeanWrapper簡化設值過程,方便后續使用;提供給子類初始化擴展點,initServletBean()
,該方法由FrameworkServlet
覆蓋。
FrameworkServlet
繼承HttpServletBean
,通過initServletBean()進行Web上下文初始化,該方法主要覆蓋一下兩件事情:初始化web上下文;提供給子類初始化擴展點。
@Override protected final void initServletBean() throws ServletException { getServletContext().log("Initializing Spring FrameworkServlet '" + getServletName() + "'"); if (this.logger.isInfoEnabled()) { this.logger.info("FrameworkServlet '" + getServletName() + "': initialization started"); } long startTime = System.currentTimeMillis(); try { this.webApplicationContext = initWebApplicationContext(); initFrameworkServlet(); } catch (ServletException ex) { this.logger.error("Context initialization failed", ex); throw ex; } catch (RuntimeException ex) { this.logger.error("Context initialization failed", ex); throw ex; } if (this.logger.isInfoEnabled()) { long elapsedTime = System.currentTimeMillis() - startTime; this.logger.info("FrameworkServlet '" + getServletName() + "': initialization completed in " + elapsedTime + " ms"); } }
DispatcherServlet繼承FrameworkServlet,並實現了onRefresh()方法提供一些前端控制器相關的配置。
整個DispatcherServlet初始化的過程和做了些什么事情,具體主要做了如下兩件事情:
1、初始化Spring Web MVC使用的Web上下文,並且指定父容器為WebApplicationContext(ContextLoaderListener加載了的根上下文);
2、初始化DispatcherServlet使用的策略,如HandlerMapping、HandlerAdapter等。
onRefresh方法代碼如下:
@Override protected void onRefresh(ApplicationContext context) { initStrategies(context); } /** * Initialize the strategy objects that this servlet uses. * <p>May be overridden in subclasses in order to initialize further strategy objects. */ protected void initStrategies(ApplicationContext context) { initMultipartResolver(context); initLocaleResolver(context); initThemeResolver(context); initHandlerMappings(context); initHandlerAdapters(context); initHandlerExceptionResolvers(context); initRequestToViewNameTranslator(context); initViewResolvers(context); initFlashMapManager(context); }
總結
1. 首先,對於一個web應用,其部署在web容器中,web容器提供其一個全局的上下文環境,這個上下文就是ServletContext,其為后面的spring IoC容器提供宿主環境;
2. 其 次,在web.xml中會提供有contextLoaderListener
。在web容器啟動時,會觸發容器初始化事件,此時 contextLoaderListener
會監聽到這個事件,其contextInitialized
方法會被調用,在這個方法中,spring會初始化一個啟動上下文,這個上下文被稱為根上下文,即WebApplicationContext
,這是一個接口類,確切的說,其實際的實現類是 XmlWebApplicationContext
。這個就是spring的IoC容器,其對應的Bean定義的配置由web.xml中的 context-param標簽指定。在這個IoC容器初始化完畢后,spring以WebApplicationContext.ROOTWEBAPPLICATIONCONTEXTATTRIBUTE
為屬性Key,將其存儲到ServletContext中,便於獲取;
3. 再 次,contextLoaderListener
監聽器初始化完畢后,開始初始化web.xml中配置的Servlet,這里是DispatcherServlet,這個servlet實際上是一個標准的前端控制器,用以轉發、匹配、處理每個servlet請 求。DispatcherServlet上下文在初始化的時候會建立自己的IoC上下文,用以持有spring mvc相關的bean。在建立DispatcherServlet自己的IoC上下文時,會利用WebApplicationContext.ROOTWEBAPPLICATIONCONTEXTATTRIBUTE
先從ServletContext中獲取之前的根上下文(即WebApplicationContext)作為自己上下文的parent上下文。有了這個 parent上下文之后,再初始化自己持有的上下文。這個DispatcherServlet初始化自己上下文的工作在其initStrategies方 法中可以看到,大概的工作就是初始化處理器映射、視圖解析等。這個servlet自己持有的上下文默認實現類也是 XmlWebApplicationContext
。初始化完畢后,spring以與servlet的名字相關(此處不是簡單的以servlet名為 Key,而是通過一些轉換,具體可自行查看源碼)的屬性為屬性Key,也將其存到ServletContext中,以便后續使用。這樣每個servlet 就持有自己的上下文,即擁有自己獨立的bean空間,同時各個servlet共享相同的bean,即根上下文(第2步中初始化的上下文)定義的那些 bean。