先来上一张类的结构图:

图里仅仅画了跟初始化相关的方法。

首先DispatcherServlet也是一个Servlet,初始化从init()方法開始。

以下就详细看看ini()是怎么实现的吧。

1.Servlet 是个接口;

    public void init(ServletConfig config) throws ServletException;

2.GenericServlet 中实现了初始化方法。

    public void init(ServletConfig config) throws ServletException {
this.config = config;
this.init();
}

这里调用了一个没有參数的init();是个空方法;

public void init() throws ServletException {

    }

3.HttpServlet 没有对初始化相关的方法进行覆盖。

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

当中又掉了一个initServletBean();方法,这本类中也是个空实现。

	protected void initServletBean() throws ServletException {
}

5.FrameworkServlet 果不其然的重写了上边留空的方法:initServletBean();

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

在这种方法中最重要的就是调用了一个initWebApplicationContext() 方法。

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

一系列的赋值和推断。最关键的,跟初始化相关的,就是调用了onRefresh(),相同的套路,这种方法在本类中为空实现。留给子类去实现。

6.最终到了DispatcherServlet,找到onRefresh()。简单!调用initStrategies(ApplicationContext context);这种方法就在下边,这下清楚了,一堆的初始化方法。详细代码就不粘了。

/**
* This implementation calls {@link #initStrategies}.
*/
@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);
}

到这里整个载入过程就理清楚了。

SpringMVC DispatcherServlet初始化过程的更多相关文章

  1. Spring框架系列(13) - SpringMVC实现原理之DispatcherServlet的初始化过程

    前文我们有了IOC的源码基础以及SpringMVC的基础,我们便可以进一步深入理解SpringMVC主要实现原理,包含DispatcherServlet的初始化过程和DispatcherServlet ...

  2. SpringMVC——DispatcherServlet的IoC容器(Web应用的IoC容器的子容器)创建过程

    在上一篇<Spring--Web应用中的IoC容器创建(WebApplicationContext根应用上下文的创建过程)>中说到了Web应用中的IoC容器创建过程.这一篇主要讲Sprin ...

  3. 【spring源码学习】springMVC之映射,拦截器解析,请求数据注入解析,DispatcherServlet执行过程

    [一]springMVC之url和bean映射原理和源码解析 映射基本过程 (1)springMVC配置映射,需要在xml配置文件中配置<mvc:annotation-driven >  ...

  4. spring自动扫描、DispatcherServlet初始化流程、spring控制器Controller 过程剖析

    spring自动扫描1.自动扫描解析器ComponentScanBeanDefinitionParser,从doScan开始扫描解析指定包路径下的类注解信息并注册到工厂容器中. 2.进入后findCa ...

  5. SpringMVC DispatcherServlet 说明与web配置

    使用Spring MVC,配置DispatcherServlet是第一步. DispatcherServlet是一个Servlet,所以能够配置多个DispatcherServlet. Dispatc ...

  6. SpringBoot对比SpringMVC,SpringMVC 处理请求过程

    (问较多:1.SpringBoot对比SpringMVC.2.SpringMVC 处理请求过程.问:springboot的理解 Spring,Spring MVC,Spring Boot 三者比较 S ...

  7. spring MVC初始化过程学习笔记1

    如果有错误请指正~ 1.springmvc容器和spring的关系? 1.1 spring是个容器,主要是管理bean,不需要servlet容器就可以启动,而springMVC实现了servlet规范 ...

  8. 深入理解Spring之九:DispatcherServlet初始化源码分析

    转载 https://mp.weixin.qq.com/s/UF9s52CBzEDmD0bwMfFw9A DispatcherServlet是SpringMVC的核心分发器,它实现了请求分发,是处理请 ...

  9. SpringMVC的启动过程

    前言 下面是一个SpringMVC应用的配置文件,需要注意两个地方,一个是ContextLoaderListener,一个是dispatcherServlet.web容器正是通过这两个配置才和spri ...

随机推荐

  1. UML-画类图与交互图的顺序

    并行.画完交互图,在画类图.交替进行.

  2. 笔试算法题(56):快速排序实现之非递归实现,最小k值选择(non-recursive version, Minimal Kth Selection of Quick Sort)

    议题:快速排序实现之五(非递归实现,短序列优先处理,减少递归栈大小) 分析: 算法原理:此算法实现适用于系统栈空间不足够快速排序递归调用的需求,从而使用非递归实现快速排序算法:使用显示下推栈存储快速排 ...

  3. 笔试算法题(25):复制拥有多个指针的链表 & 判断二元树B是否为A的子树

    出题:定义一个复杂链表:在单向链表的基础上,每个节点附加一个指向链表中其他任意节点的指针sibling,实现CNode* Clone(Cnode *head)函数复制这个复杂链表: 分析: 解法1:将 ...

  4. 图解C/C++多级指针与多维数组

    声明:本文转自 chenyang_yao ,欢迎阅读原文. 指针与数组是C/C++编程中非常重要的元素,同时也是较难以理解的.其中,多级指针与“多维”数组更是让很多人云里雾里,其实,只要掌握一定的方法 ...

  5. 简单说一下Set,list,Map的类型和自己的特点

    首先是Set,List,Map Set和list都是继承了Conllection接口,而Map是本身就是一个接口 set是最简单的一种集合,没有重复对象 set接口主要有两个实现: 1,hashSet ...

  6. Nginx出现403 forbidden (13: Permission denied)报错的四种原因

    一.由于php-fpm启动用户和nginx工作用户不一致所致 php-fpm启动用户配置位置 nginx工作用户配置位置 二.不存在在文件,可能是文件路径有误,可以查看nginx错误日志来判断 三.缺 ...

  7. 关于Python构建微服务的思考(一)

    一:什么是微服务? 微服务是一种架构风格,一个大型复杂软件应用由一个或多个微服务组成. 系统中的各个微服务可被独立部署,各个微服务之间是松耦合的. 每个微服务仅关注于完成一件任务并很好地完成该任务. ...

  8. ORM之连表操作

    ORM之连表操作 -----------------------------连表的正向操作------------------------- 在models.py中创建两张表UserType和User ...

  9. IOC&DI

    [概述] 1.IOC(Inversion of Control): 即“反转控制”,不是什么技术,而是一种设计思想.其思想是反转资源获取的方向. 传统的资源查找方式要求组件向容器发起请求查找资源.作为 ...

  10. VS2015 scanf用不了

    #define _CRT_SECURE_NO_DEPRECATE