1.说明

SpringMVC作为Spring提供的MVC实现,可以实现与Spring的天然无缝联合,因为具有很广泛的用途。具体的关于SpringMVC的处理流程逻辑我在这里就不在赘述了。还是来通过源码来追述下SpringMVC的启动过程。

2.入口

DispatcherServlet作为SpringMVC的前端控制器,具有很核心的地位。来看下它的继承结构。

可以看到DispatcherServlet依次继承了GenericServlet、HttpServlet、HttpServletBean、FrameworkServlet.由于DispatcherServlet是继承了HttpServlet,所以它的初始化入口应该是HttpServlet的init()方法,Web容器启动时将调用它的init方法init()方法具体做了什么工作。

	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");
}
}

  注意这个方法是final,不能够被覆盖,它位于HttpServletBean中。它完成的功能有两个,第一个将将Servlet初始化参数设置到该Servlet中,第二个调用子类的初始化。

3.HttpServletBean的 initServletBean()

从上面可知,initServletBean方法主要用于子类的处理话过程。看下HttpServletBean的子类FrameworkServlet.看下具体的实现:

	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");
}
}

  FrameworkServlet是SpringMVC的一个基础Servlet,通过它可以完成和Spring的整合。通过initServletBean()的代码,可知只要操作有两个initWebApplicationContext();和initFrameworkServlet();第一个完成了Web上下文的初始化工作:ContextLoaderListener 加载了上下文将作为根上下文(DispatcherServlet 的父容器),第二个则提供给子类进行初始化的扩展点:行容器的一些初始化,这个方法由子类实现,来进行扩展。。

我们来看下它是如何完成Web上下文的初始化工作 initWebApplicationContext(); 实现代码:

	protected WebApplicationContext initWebApplicationContext() {
WebApplicationContext rootContext =
WebApplicationContextUtils.getWebApplicationContext(getServletContext());
WebApplicationContext wac = null; if (this.webApplicationContext != null) {
//在创建的时候注入根上下文
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
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;
}

  它首先通过Spring提供的工具类 WebApplicationContextUtils 获取Spring 的根上下文(ContextLoaderListener加载的)。主要操作有1.在创建该Servlet的时候注入根上下文,2.如果上下文为空,那么就查找已经绑定的上下文,如下所示

	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;
}

  第三个操作,如果没有找到相应的上下文,并指定父亲为ContextLoaderListener,手动创建一个

	protected WebApplicationContext createWebApplicationContext(ApplicationContext parent) {
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");
}
ConfigurableWebApplicationContext wac =
(ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass); wac.setEnvironment(getEnvironment());
wac.setParent(parent);
wac.setConfigLocation(getContextConfigLocation()); configureAndRefreshWebApplicationContext(wac); return wac;
}

  第四步,不管这个上下文是不是ConfigurableApplicationContext或者在构建的时候刷新过,都需要重新刷新上下文,完成一些初始化的工作。

第四步的实现是放到DispatcherServlet中的onRefresh实现的,具体来看代码,

	@Override
protected void onRefresh(ApplicationContext context) {
initStrategies(context);
} protected void initStrategies(ApplicationContext context) {
initMultipartResolver(context);
initLocaleResolver(context);
initThemeResolver(context);
initHandlerMappings(context);
initHandlerAdapters(context);
initHandlerExceptionResolvers(context);
initRequestToViewNameTranslator(context);
initViewResolvers(context);
initFlashMapManager(context);
}

  

它主要完成了控制器相关的配置工作,具体工作。。。。好多。。暂缓。

4.总结

SpringMVC初始化启动过程中做的事情比较简单,初始化 Spring Web MVC 使用的 Web 上下文并且指定ContextLoaderListener为父容器;还有就是上面代码所示的那样初始DispatcherServlet 使用的策略。

未完待续!!!!!!!!

Spring之SpringMVC(源码)启动初始化过程分析的更多相关文章

  1. MyBatis、Spring、SpringMVC 源码下载地址

    MyBatis.Spring.SpringMVC 源码下载地址 github mybatis https://github.com/fengyu415/MyBatis-Learn.git spring ...

  2. springmvc源码解析-初始化

    1.      概述 对于Web开发者,MVC模型是大家再熟悉不过的了,SpringMVC中,满足条件的请求进入到负责请求分发的DispatcherServlet,DispatcherServlet根 ...

  3. Java工程师学习指南第3部分:Spring与SpringMVC源码解析

    本文整理了微信公众号[Java技术江湖]发表和转载过的Spring全家桶优质文章,想看到更多Java技术文章,就赶紧关注吧. 前后端分离,我怎么就选择了 Spring Boot + Vue 技术栈? ...

  4. Spring之SpringMVC(源码)初始化DispatcherServlet策略配置

    1.从上一篇文章中可以SpringMVC初始化的过程中完成的其中一件事就是DispatcherServlet的相关策略的配置,如下所示 protected void initStrategies(Ap ...

  5. SpringMVC源码分析--容器初始化(五)DispatcherServlet

    上一篇博客SpringMVC源码分析--容器初始化(四)FrameworkServlet我们已经了解到了SpringMVC容器的初始化,SpringMVC对容器初始化后会进行一系列的其他属性的初始化操 ...

  6. springMVC源码分析--容器初始化(二)DispatcherServlet

    在上一篇博客springMVC源码分析--容器初始化(一)中我们介绍了spring web初始化IOC容器的过程,springMVC作为spring项目中的子项目,其可以和spring web容器很好 ...

  7. SpringMVC源码分析--容器初始化(四)FrameworkServlet

    在上一篇博客SpringMVC源码分析--容器初始化(三)HttpServletBean我们介绍了HttpServletBean的init函数,其主要作用是初始化了一下SpringMVC配置文件的地址 ...

  8. SpringMVC源码分析--容器初始化(三)HttpServletBean

    在上一篇博客springMVC源码分析--容器初始化(二)DispatcherServlet中,我们队SpringMVC整体生命周期有一个简单的说明,并没有进行详细的源码分析,接下来我们会根据博客中提 ...

  9. Spring IOC 容器源码分析 - 余下的初始化工作

    1. 简介 本篇文章是"Spring IOC 容器源码分析"系列文章的最后一篇文章,本篇文章所分析的对象是 initializeBean 方法,该方法用于对已完成属性填充的 bea ...

随机推荐

  1. Java 新特性(4) - JDK 8 新特性

    http://www.360doc.com/content/14/0620/11/1370831_388286071.shtml

  2. 解决LINUX vncserver 启动 could not open default font &#39;fixed&#39;错.

    安装vncserver例如,会发生以下错误:  vncext:      VNC extension running!  vncext:      Listening for VNC connecti ...

  3. eclipse android ndk 提示Type 'JNIEnv' could not be resolved 等信息解决办法

    新配置完eclipse c++ android ndk 环境后,导入项目提示以下信息 是由于没有将jni.h导入的缘故,而这个文件在ndk的目录下面.所以,参照以下步骤:Project Propert ...

  4. [ExtJS5学习笔记]第22 Extjs5正在使用beforeLabelTpl添加所需的配置选项标注星号标记

    本文地址:http://blog.csdn.net/sushengmiyan/article/details/39395753 官方样例:http://docs.sencha.com/extjs/5. ...

  5. Redis相关命令及Jedis的demo(转)

    org.springframework.data.redis.core.RedisTemplate在List操作时的一个注意事项:BoundListOperations boundListOperat ...

  6. 高性能 TCP &amp; UDP 通信框架 HP-Socket v3.2.3 正式公布

    HP-Socket 是一套通用的高性能 TCP/UDP 通信框架,包括服务端组件.client组件和 Agent 组件,广泛适用于各种不同应用场景的 TCP/UDP 通信系统,提供 C/C++.C#. ...

  7. hdu 5072 Coprime(同色三角形+容斥)

    pid=5072">http://acm.hdu.edu.cn/showproblem.php?pid=5072 单色三角形模型 现场赛和队友想了3个小时,最后发现想跑偏了.感觉好可惜 ...

  8. eclipse环境下如何配置tomcat

    eclipse环境下如何配置tomcat 很多初学,尤其自学JavaWeb的朋友首次在eclipse下配置tomcat时,总会有种难下手的感觉,在此,通过图文解说的方法,最直观的向大家演示一遍该配置过 ...

  9. (大数据工程师学习路径)第三步 Git Community Book----中级技能(下)

    一.追踪分支 1.追踪分支 在Git中‘追踪分支’是用于联系本地分支和远程分支的. 如果你在’追踪分支'(Tracking Branches)上执行推送(push)或拉取(pull)时,它会自动推送( ...

  10. eclipse+Java2WSDL+WSDL2Java 2012-12-06 12:32:43| 分类: j2ee |报道|字体大小 认购 一、eclipse如何使用低axis生成wsdl 可以使用

    eclipse+Java2WSDL+WSDL2Java 一.eclipse下怎样用axis生成wsdl 能够使用axis提供的Java2WSDL功能生成所要公布类的 WSDL,过程例如以下:  1.在 ...