DispatcherServlet 的初始化
Spring MVC 是基於 Servlet 功能實現的,通過實現 Servlet 接口的 DispatcherServlet 來封裝其核心功能實現,通過將請求分派給處理程序,同時帶有可配置的處理程序映射、視圖解析、本地語言、主題解析以及上載文件支持。下面是 DispatcherServlet 的繼承圖:
servlet 初始化階段會調用其 init 方法,所以我們首先要查看在 DispatcherServlet 中是否重寫了 init 方法。我們在其父類 HttpServletBean 中找到了該方法。
HttpServletBean.java
public final void init() throws ServletException {
if (logger.isDebugEnabled()) {
logger.debug("Initializing servlet '" + getServletName() + "'");
}
// Set bean properties from init parameters.
try {
// 解析 init-param 並封裝只 pvs 中
PropertyValues pvs = new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties);
// 將當前的這個 Servlet 類轉化爲一個 BeanWrapper,從而能夠以 Spring 的方法來對 init-param 的值進行注入
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
ResourceLoader resourceLoader = new ServletContextResourceLoader(getServletContext());
// 註冊自定義屬性編輯器,一旦遇到 Resource 類型的屬性將會使用 ResourceEditor 進行解析
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");
}
}
初始化的主要過程時序圖如下:
DipatcherServlet 的初始化過程主要是通過將當前的 servlet 類型實例轉換爲 BeanWrapper 類型實例,以便使用 Spring 中提供的注入功能進行對應屬性的注入。這些屬性如 contextAttribute、contextClass、nameSpace、contextConfigLocation 等,都可以在 web.xml 文件中以初始化參數的方式配置在 servlet 的聲明中。DispatcherServlet 繼承自 FrameworkServlet,FrameworkServlet 類上包含對應的同名屬性,Spring 會保證這些參數被注入到對應的值中。屬性注入主要包含以下幾個步驟:
1.封裝及驗證初始化參數
ServletConfigPropertyValues 除了封裝屬性外還有對屬性驗證的功能。
HttpServletBean.java
public ServletConfigPropertyValues(ServletConfig config, Set<String> requiredProperties)
throws ServletException {
Set<String> missingProps = (requiredProperties != null && !requiredProperties.isEmpty()) ?
new HashSet<String>(requiredProperties) : null;
Enumeration<String> en = config.getInitParameterNames();
while (en.hasMoreElements()) {
String property = en.nextElement();
Object value = config.getInitParameter(property);
addPropertyValue(new PropertyValue(property, value));
if (missingProps != null) {
missingProps.remove(property);
}
}
// Fail if we are still missing properties.
if (missingProps != null && missingProps.size() > 0) {
throw new ServletException(
"Initialization from ServletConfig for servlet '" + config.getServletName() +
"' failed; the following required properties were missing: " +
StringUtils.collectionToDelimitedString(missingProps, ", "));
}
}
從代碼中得知,封裝屬性主要是對初始化的參數進行封裝,也就是 servlet 中配置的 <init-param> 中配置的封裝。當然,用戶可以通過對 requiredProperties 參數的初始化來強制驗證某些屬性的必然性,這樣,在屬性封裝的過程中,一旦檢測到 requiredProperties 中的屬性沒有指定初始值,就會拋出異常。
2.將當前 servlet 實例轉化成 BeanWrapper 實例
PropertyAccessorFactory.forBeanPropertyAccess 是Spring 中提供的工具方法,主要用於將指定實例轉化爲 Spring 中可以處理的 BeanWrapper 類型的實例。
3.註冊相對於 Resource 的屬性編輯器
屬性編輯器,我們在上文中已經介紹並且分析過其原理,這裏使用屬性編輯器的目的是在對當前實例(DispatcherServlet)屬性注入過程中一旦遇到 Resource 類型的屬性就會使用 ResourceEditor 去解析。
4.屬性注入
BeanWrapper 爲 Spring 中的方法,支持 Spring 的自動注入。其實我們最常用的屬性注入無非是 contextAttribute、contextClass、nameSpace、contextConfigLocation 等屬性。
5.servletBean 的初始化
在 ContextLoaderListener 加載的時候已經創建了 WebApplicationContext 實例,而在這個函數中最重要的就是對這個實例進行進一步的補充初始化。
繼續查看 initServletBean()。父類 FrameworkServlet 覆蓋了 HttpServletBean 中的 initServletBean 函數,如下:
FrameworkServlet.java
@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");
}
}
上面的函數設計了計時器來統計初始化的執行時間,而且提供了一個擴展方法 initFrameworkServlet() 用於子類的覆蓋操作,而作爲關鍵的初始化邏輯實現委託給了 initWebApplicationContext();
WebApplicationContext 的初始化
initWebApplicationContext 函數
initWebApplicationContext 函數的主要工作就是創建或刷新 WebApplicationContext 實例並對 servlet 功能所使用的組件進行初始化。
FrameworkServlet.java
protected WebApplicationContext initWebApplicationContext() {
WebApplicationContext rootContext =
WebApplicationContextUtils.getWebApplicationContext(getServletContext());
WebApplicationContext wac = null;
if (this.webApplicationContext != null) {
// A context instance was injected at construction time -> use it
// context 實例在構造函數中被注入
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) {
// No context instance was injected at construction time -> see if one
// has been registered in the servlet context. If one exists, it is assumed
// that the parent context (if any) has already been set and that the
// user has performed any initialization such as setting the context id
// 根據 contextAttribute 屬性加載 WebApplicationContext
wac = findWebApplicationContext();
}
if (wac == null) {
// No context instance is defined for this servlet -> create a local one
wac = createWebApplicationContext(rootContext);
}
if (!this.refreshEventReceived) {
// Either the context is not a ConfigurableApplicationContext with refresh
// support or the context injected at construction time had already been
// refreshed -> trigger initial onRefresh manually here.
onRefresh(wac);
}
if (this.publishContext) {
// Publish the context as a servlet context attribute.
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 + "]");
}
}
return wac;
}
對於本函數中的初始化主要包含以下幾個部分:
1. 尋找或創建 WebApplicationContext 實例。
2. WebApplicationContext 的配置。
3. WebApplicationContext 的刷新。
尋找或創建 WebApplicationContext 實例
WebApplicationContext 的尋找及創建包括以下幾個步驟。
(1)通過構造函數的注入進行初始化。
當進入 initWebApplicationContext 函數後通過判斷 this.webApplicationContext != null 後,便可以確定 this.webApplicationContext 是否是通過構造函數來初始化的。可是有讀者可能會有疑問,在 initServletBean 函數中明明是把創建好的實例記錄在了 this.webApplicationContext 中:
this.webApplicationContext = initWebApplicationContext();
何以判定這個參數是通過構造函數初始化,而不是通過上一次的函數返回值初始化呢?如果存在這個問題,那麼就是讀者忽略一個問題了:在 Web 中包含 SpringWeb 的核心邏輯的 DispatcherServlet 只可以被聲明爲一次,在 Spring 中已經存在驗證,所以這就確保瞭如果 this.webApplicationContext != null,則可以直接判定 this.webApplicationContext 已經通過構造函數初始化。
(2)通過 contextAttribute 進行初始化
通過在 web.xml 文件中配置的 servlet 參數 contextAttribute 來查找 ServletContext 中對應的屬性,默認爲 WebApplicationContext.class.getName() + ".ROOT",也就是在 ContextLoaderListener 加載時會創建 WebApplicationContext 實例,並將實例以 WebApplicationContext.class.getName() + ".ROOT" 爲 key 放入 ServletContext 中,當然讀者可以重寫初始化邏輯使用自己創建的 WebApplicationContext,並在 servlet 的配置中通過初始化參數 contextAttribute 指定 key。
FrameworkServlet.java
protected WebApplicationContext findWebApplicationContext() {
String attrName = getContextAttribute();
if (attrName == null) {
return null;
}
WebApplicationContext wac =
WebApplicationContextUtils.getWebApplicationContext(getServletContext(), attrName);
if (wac == null) {
throw new IllegalStateException("No WebApplicationContext found: initializer not registered?");
}
return wac;
}
(3)重新創建 WebApplicationContext 實例。
如果通過以上兩種方式並沒有找到任何突破,那就沒辦法了,只能在這裏重新創建新的實例了。
FrameworkServlet.java
protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) {
return createWebApplicationContext((ApplicationContext) parent);
}
protected WebApplicationContext createWebApplicationContext(ApplicationContext parent) {
// 獲取 servlet 的初始化參數 contextClass,如果沒有配置默認爲 XMLWebApplicationContext.Class
Class<?> contextClass = getContextClass();
if (this.logger.isDebugEnabled()) {
this.logger.debug("Servlet with name '" + getServletName() +
"' will try to create custom WebApplicationContext context of class '" +
contextClass.getName() + "'" + ", using parent context [" + parent + "]");
}
if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
throw new ApplicationContextException(
"Fatal initialization error in servlet with name '" + getServletName() +
"': custom WebApplicationContext class [" + contextClass.getName() +
"] is not of type ConfigurableWebApplicationContext");
}
// 通過反射方式實例化 contextClass
ConfigurableWebApplicationContext wac =
(ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
// parent 爲在 ContextLoaderListener 中創建的實例
// 在 ContextLoaderListener 加載的時候初始化的 WebApplicationContext 類型實例
wac.setEnvironment(getEnvironment());
wac.setParent(parent);
// 獲取 contextConfigLocation 屬性,配置在 servlet 初始化參數中
wac.setConfigLocation(getContextConfigLocation());
// 初始化 Spring 環境包括加載配置文件等
configureAndRefreshWebApplicationContext(wac);
return wac;
}
WebApplicationContext 的配置
無論是通過構造函數注入還是單獨創建,都免不了會調用 configureAndRefreshWebApplicationContext 方法來對已經創建的 WebApplicationContext 實例進行配置及刷新,那麼這個步驟又做哪些工作呢?
FrameworkServlet.java
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac) {
if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
// The application context id is still set to its original default value
// -> assign a more useful id based on available information
if (this.contextId != null) {
wac.setId(this.contextId);
}
else {
// Generate default id...
wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
ObjectUtils.getDisplayString(getServletContext().getContextPath()) + "/" + getServletName());
}
}
wac.setServletContext(getServletContext());
wac.setServletConfig(getServletConfig());
wac.setNamespace(getNamespace());
wac.addApplicationListener(new SourceFilteringListener(wac, new ContextRefreshListener()));
// The wac environment's #initPropertySources will be called in any case when the context
// is refreshed; do it eagerly here to ensure servlet property sources are in place for
// use in any post-processing or initialization that occurs below prior to #refresh
ConfigurableEnvironment env = wac.getEnvironment();
if (env instanceof ConfigurableWebEnvironment) {
((ConfigurableWebEnvironment) env).initPropertySources(getServletContext(), getServletConfig());
}
postProcessWebApplicationContext(wac);
applyInitializers(wac);
// 加載配置文件及整合 parent 到 wac
wac.refresh();
}
無論調用方式如何變化,只要是使用 AlicationContext 所提供的功能最後都免不了使用公共父類 AbstractApplicationContext 提供的 refresh() 進行配置文件加載。
WebApplicationContext 的刷新
onRefresh 是 FrameworkServlet 類中提供的模板方法,在其子類 DispatcherServlet 中進行了重寫,主要用於刷新 Spring 在 Web 功能實現中所必須使用的組件。下面我們會介紹它們的初始化過程以及使用場景,而至於具體的使用細節會在稍後的章節中再做詳細介紹。
DispatcherServlet.java
@Override
protected void onRefresh(ApplicationContext context) {
initStrategies(context);
}
protected void initStrategies(ApplicationContext context) {
// 1.初始化 MultipartResolver
initMultipartResolver(context);
// 2.初始化 LocaleResolver
initLocaleResolver(context);
// 3.初始化 ThemeResolver
initThemeResolver(context);
// 4.初始化 HandlerMappings
initHandlerMappings(context);
// 5.初始化 HandlerAdapters
initHandlerAdapters(context);
// 6.初始化 HandlerExceptionResolvers
initHandlerExceptionResolvers(context);
// 7.初始化 RequestToViewNameTranslator
initRequestToViewNameTranslator(context);
// 8.初始化 ViewResolvers
initViewResolvers(context);
// 9.初始化 FlashMapManager
initFlashMapManager(context);
}
initStrategies 的具體內容非常簡單,就是初始化的 9 個組件。
HandlerMapping 的初始化
對於具體的初始化過程,根據上面的方法名稱,很容易理解。以 HandlerMapping 爲例來說明這個 initHandlerMappings() 過程。這裏的 Mapping 關係的作用是,爲 HTTP 請求找到相應的 Controller 控制器,從而利用這些控制器 Controller 去完成設計好的數據處理工作。HandlerMappings 完成對 MVC 中 Controller 的定義和配置,只不過在 Web 這個特定的應用環境中,這些控制器是與具體的 HTTP 請求相對應的。DispatcherServlet 中 HandlerMappings 初始化過程的具體實現。在 HandlerMapping 初始化的過程中,把在 Bean 配置文件中配置好的 handlerMapping 從 Ioc 容器中取得。
private void initHandlerMappings(ApplicationContext context) {
this.handlerMappings = null;
// 這裏導入所有的 HandlerMapping Bean,這些 Bean 可以在當前的 DispatcherServlet 的
// Ioc 容器中,也可能在其雙親上下文中
// 這個 detectAllHandlerMappings 的默認值設爲 true,即默認地從所有的 Ioc 容器中取
if (this.detectAllHandlerMappings) {
// Find all HandlerMappings in the ApplicationContext, including ancestor contexts.
Map<String, HandlerMapping> matchingBeans =
BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerMapping.class, true, false);
if (!matchingBeans.isEmpty()) {
this.handlerMappings = new ArrayList<HandlerMapping>(matchingBeans.values());
// We keep HandlerMappings in sorted order.
AnnotationAwareOrderComparator.sort(this.handlerMappings);
}
}
else {
// 可以根據名稱從當前的 Ioc 容器中通過 getBean 獲取 handlerMapping
try {
HandlerMapping hm = context.getBean(HANDLER_MAPPING_BEAN_NAME, HandlerMapping.class);
this.handlerMappings = Collections.singletonList(hm);
}
catch (NoSuchBeanDefinitionException ex) {
// Ignore, we'll add a default HandlerMapping later.
}
}
// Ensure we have at least one HandlerMapping, by registering
// a default HandlerMapping if no other mappings are found.
// 如果沒有找到 handerMappings,那麼需要爲 servlet 設定默認的 handlerMappings,這些默認
// 值可以設置在 DispatcherServlet.properties 中
if (this.handlerMappings == null) {
this.handlerMappings = getDefaultStrategies(context, HandlerMapping.class);
if (logger.isDebugEnabled()) {
logger.debug("No HandlerMappings found in servlet '" + getServletName() + "': using default");
}
}
}
經過以上的讀取過程,handlerMapping 變量就已經獲取了在 BeanDefinition 中配置好的映射關係。其他的初始化過程和 handlerMapping 比較類似,都是自己從 Ioc 容器中讀入配置,所以這裏的 MVC 初始化過程是建立在 Ioc 容器已經初始化完成的基礎上的。