SpringMVC DispatcherServlet原始碼解析
DispatcherServlet繼承關係
初始化過程分析
* 呼叫HttpServletBean的init方法(內部的initServletBean方法是空方法,交由FrameworkServlet實現)
DispatcherServlet中沒有定義init方法,是從httpservlet中繼承過來的,在HttpServletBean中重寫
HttpServletBean中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");
}
}
1. 先看下第一行程式碼,建立一個PropertyValues
將servletconfig獲取到的servlet的初始化引數和值,建立propertyvalue物件,新增到propertyValueList中
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, ", "));
}
}
}
2. 給當前的物件生成BeanWrapper物件(這個BeanWrapper類是一個不通過建立物件,通過建立PropertyValue設定物件的屬性值) ,關於BeanWrapper的介紹
3. 呼叫BeanWrapper物件的setPropertyValues,設定DispatcherServlet的初始化引數。
4. 呼叫initServletBean方法,在HTTPServletBean中是空方法,由DispatcherServlet的上一級父類FrameworkServlet實現
protected void initServletBean() throws ServletException {
}
FrameworkServlet的initServletBean方法
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");
}
}
建立webApplicationContext(這個介面繼承自ApplicationContext)並設定到ServletContext中,這樣將web容器和Spring上下文關聯起來了。
具體細節
protected WebApplicationContext initWebApplicationContext() {
//獲取根上下文
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);
}
//設定webApplicationContext
configureAndRefreshWebApplicationContext(cwac);
}
}
}
if (wac == null) {
//根據contextAttribute屬性來獲取webapplicationContext,一般設定DispatcherServlet的屬性時候不設定,這裡就不執行
wac = findWebApplicationContext();
}
if (wac == null) {
//DispatcherServlet初始化最終呼叫的方法,建立上下文,並配置上下文的父上下文
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);//將建立的容器上下文設定到ServletContext中
if (this.logger.isDebugEnabled()) {
this.logger.debug("Published WebApplicationContext of servlet '" + getServletName() +
"' as ServletContext attribute with name [" + attrName + "]");
}
}
return wac;
}
這裡的根上下文是web.xml中配置的ContextLoaderListener監聽器中根據contextConfigLocation路徑生成的上下文。
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springConfig/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
onRefresh方法會在DispatcherServlet中重寫,用於初始化springMVC的元件
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. HttpServletBean
將web.xml中配置的servlet引數設定到DispatcherServlet的屬性上
2. FrameworkServlet
建立WebApplicationContext並設定到ServletContext上,將SpringMVC的上下文和servlet容器關聯,
WebApplicationContext有個父類的上下文,既web.xml中配置的ContextLoaderListener監聽器初始化的容器上下文。
3.DispatcherServlet
初始化springMVC依賴的各個元件
參考: http://www.cnblogs.com/fangjian0423/p/springMVC-dispatcherServlet.html
相關文章
- SpringMVC原始碼解析系列2-DispatcherServletSpringMVC原始碼Servlet
- SpringMVC系列原始碼:DispatcherServletSpringMVC原始碼Servlet
- SpringMVC 解析(二)DispatcherServletSpringMVCServlet
- springmvc原始碼 ---DispatcherServlet 處理請求SpringMVC原始碼Servlet
- SpringMVC原始碼分析2:SpringMVC設計理念與DispatcherServletSpringMVC原始碼Servlet
- SpringMVC原始碼剖析(二)- DispatcherServlet的前世今生SpringMVC原始碼Servlet
- SpringMVC原始碼剖析(三)- DispatcherServlet的初始化流SpringMVC原始碼Servlet
- SpringMVC原始碼剖析(三)- DispatcherServlet的初始化流程SpringMVC原始碼Servlet
- SpringMVC原始碼解析SpringMVC原始碼
- SpringMVC原始碼解析(上)SpringMVC原始碼
- SpringMVC原始碼解析(下)SpringMVC原始碼
- SpringMVC原始碼剖析(四)- DispatcherServlet請求轉發的實現SpringMVC原始碼Servlet
- 【spring原始碼學習】springMVC之對映,攔截器解析,請求資料注入解析,DispatcherServlet執行過程原始碼SpringMVCServlet
- SpringMVC原始碼分析3:DispatcherServlet的初始化與請求轉發SpringMVC原始碼Servlet
- 深入瞭解SpringMVC原始碼解析SpringMVC原始碼
- springMVC DispatcherServlet 初始化SpringMVCServlet
- springMVC DispatcherServlet 工作流程SpringMVCServlet
- SpringMVC原始碼關於檢視解析渲染SpringMVC原始碼
- SpringMVC原始碼解析系列4-HandleAdapterSpringMVC原始碼APT
- SpringMVC原始碼解析(1)-啟動過程SpringMVC原始碼
- SpringMVC原始碼之引數解析繫結原理SpringMVC原始碼
- SpringMVC原始碼解析系列3-HandleMappingSpringMVC原始碼APP
- Spring MVC 解析之 DispatcherServletSpringMVCServlet
- SpringMVC原始碼分析SpringMVC原始碼
- Spring 原始碼解析一:SpringMVC 的載入機制原始碼SpringMVC
- SpringMVC原始碼分析1:SpringMVC概述SpringMVC原始碼
- SpringMVC原始碼解析 - HandlerAdater - ModelAndViewContainer上下文容器SpringMVC原始碼ViewAI
- SpringMVC原始碼分析原理SpringMVC原始碼
- 【原始碼解析】- ArrayList原始碼解析,絕對詳細原始碼
- springMvc原始碼學習之:spring原始碼總結SpringMVC原始碼
- springmvc工作原理及原始碼分析SpringMVC原始碼
- SpringMVC請求流程原始碼分析SpringMVC原始碼
- SpringMVC基礎原始碼分析(一)SpringMVC原始碼
- SpringMVC原始碼系列:AbstractUrlHandlerMappingSpringMVC原始碼APP
- SpringMVC原始碼分析系列(精簡)SpringMVC原始碼
- SpringMVC原始碼系列:AbstractHandlerMappingSpringMVC原始碼APP
- SpringMVC原始碼系列:HandlerMappingSpringMVC原始碼APP
- springMvc Velocity tool 原始碼分析SpringMVC原始碼