spring的启动是建筑在servlet容器之上的,所有web工程的初始位置就是web.xml,它配置了servlet的上下文(context)和监听器(Listener),下面就来看看web.xml里面的配置:

  1.   <!--上下文监听器,用于监听servlet的启动过程-->
  2.   <listener>
  3. <description>ServletContextListener</description>
  4. <!--这里是自定义监听器,个性化定制项目启动提示-->
  5. <listener-class>com.trace.app.framework.listeners.ApplicationListener</listener-class>
  6. </listener>
  7.  
  8.   <!--dispatcherServlet的配置,这个servlet主要用于前端控制,这是springMVC的基础-->
  9. <servlet>
  10. <servlet-name>service_dispatcher</servlet-name>
  11. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  12. <init-param>
  13. <param-name>contextConfigLocation</param-name>
  14. <param-value>/WEB-INF/spring/services/service_dispatcher-servlet.xml</param-value>
  15. </init-param>
  16. <load-on-startup>1</load-on-startup>
  17. </servlet>
  18.  
  19.   <!--spring资源上下文定义,在指定地址找到spring的xml配置文件-->
  20. <context-param>
  21. <param-name>contextConfigLocation</param-name>
  22. <param-value>/WEB-INF/spring/application_context.xml</param-value>
  23. </context-param>
  24.   <!--spring的上下文监听器-->
  25. <listener>
  26. <listener-class>
  27. org.springframework.web.context.ContextLoaderListener
  28. </listener-class>
  29. </listener>
  30.  
  31.   <!--Session监听器,Session作为公共资源存在上下文资源当中,这里也是自定义监听器-->
  32. <listener>
  33. <listener-class>
  34. com.trace.app.framework.listeners.MySessionListener
  35. </listener-class>
  36. </listener>

  接下来就一点的来解析这样一个启动过程。

1. spring的上下文监听器

  代码如下:

  1. <!--spring资源上下文定义,在指定地址找到spring的xml配置文件-->
  2. <context-param>
  3. <param-name>contextConfigLocation</param-name>
  4. <param-value>/WEB-INF/spring/application_context.xml</param-value>
  5. </context-param>
  6. <!--spring的上下文监听器-->
  7. <listener>
  8. <listener-class>
  9. org.springframework.web.context.ContextLoaderListener
  10. </listener-class>
  11. </listener>

  spring的启动其实就是IOC容器的启动过程,通过上述的第一段配置<context-param>是初始化上下文,然后通过后一段的的<listener>来加载配置文件,其中调用的spring包中的ContextLoaderListener这个上下文监听器,ContextLoaderListener是一个实现了ServletContextListener接口的监听器,他的父类是 ContextLoader,在启动项目时会触发contextInitialized上下文初始化方法。下面我们来看看这个方法:

  1. public void contextInitialized(ServletContextEvent event) {
  2. initWebApplicationContext(event.getServletContext());
  3. }

  可以看到,这里是调用了父类ContextLoaderinitWebApplicationContext(event.getServletContext());方法,很显然,这是对ApplicationContext的初始化方法,也就是到这里正是进入了springIOC的初始化。

  接下来再来看看initWebApplicationContext又做了什么工作,先看看代码:

  1.     if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {
  2. throw new IllegalStateException(
  3. "Cannot initialize context because there is already a root application context present - " +
  4. "check whether you have multiple ContextLoader* definitions in your web.xml!");
  5. }
  6.  
  7. Log logger = LogFactory.getLog(ContextLoader.class);
  8. servletContext.log("Initializing Spring root WebApplicationContext");
  9. if (logger.isInfoEnabled()) {
  10. logger.info("Root WebApplicationContext: initialization started");
  11. }
  12. long startTime = System.currentTimeMillis();
  13.  
  14. try {
  15. // Store context in local instance variable, to guarantee that
  16. // it is available on ServletContext shutdown.
  17. if (this.context == null) {
  18. this.context = createWebApplicationContext(servletContext);
  19. }
  20. if (this.context instanceof ConfigurableWebApplicationContext) {
  21. ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
  22. if (!cwac.isActive()) {
  23. // The context has not yet been refreshed -> provide services such as
  24. // setting the parent context, setting the application context id, etc
  25. if (cwac.getParent() == null) {
  26. // The context instance was injected without an explicit parent ->
  27. // determine parent for root web application context, if any.
  28. ApplicationContext parent = loadParentContext(servletContext);
  29. cwac.setParent(parent);
  30. }
  31. configureAndRefreshWebApplicationContext(cwac, servletContext);
  32. }
  33. }
  34. servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
  35.  
  36. ClassLoader ccl = Thread.currentThread().getContextClassLoader();
  37. if (ccl == ContextLoader.class.getClassLoader()) {
  38. currentContext = this.context;
  39. }
  40. else if (ccl != null) {
  41. currentContextPerThread.put(ccl, this.context);
  42. }
  43.  
  44. if (logger.isDebugEnabled()) {
  45. logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" +
  46. WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]");
  47. }
  48. if (logger.isInfoEnabled()) {
  49. long elapsedTime = System.currentTimeMillis() - startTime;
  50. logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms");
  51. }
  52.  
  53. return this.context;
  54. }
  55. catch (RuntimeException ex) {
  56. logger.error("Context initialization failed", ex);
  57. servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
  58. throw ex;
  59. }
  60. catch (Error err) {
  61. logger.error("Context initialization failed", err);
  62. servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err);
  63. throw err;
  64. }

  这个方法还是有点长的,其实仔细看看,出去异常错误处理,这个方法主要做了三件事:

  1. 创建WebApplicationContext。
  2. 加载对应的spring配置文件中的Bean。
  3. 将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值常量。

  1. servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);

  总结来说如下图:

        

2.SpringMVC的启动过程

  web.xml的相关配置:

  1. <!--dispatcherServlet的配置,这个servlet主要用于前端控制,这是springMVC的基础-->
  2. <servlet>
  3. <servlet-name>service_dispatcher</servlet-name>
  4. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  5. <init-param>
  6. <param-name>contextConfigLocation</param-name>
  7. <param-value>/WEB-INF/spring/services/service_dispatcher-servlet.xml</param-value>
  8. </init-param>
  9. <load-on-startup>1</load-on-startup>
  10. </servlet>

  这里采用这种自定义初始化参数的配置方式,当然也可以使用默认的。这里Spring Web MVC框架将加载“classpath:service_dispatcher-servlet.xml”来进行初始化上下文而不是“/WEB-INF/[servlet名字]-servlet.xml”。

  通过上述配置文件很明显可以看出,springMVC的起始位置是DispatcherServlet(还是spring提供的)

  1. public class DispatcherServlet extends FrameworkServlet {
  2. ... ...
  3. }

  这个类的父类是FrameworkServletFrameworkServlet又继承了HttpServletBean类,HttpServletBean又继承了HttpServletHttpServlet继承了GenericServlet

  1. public abstract class FrameworkServlet extends HttpServletBean implements ApplicationContextAware {
  2. ... ...
  3. }
  4. public abstract class HttpServletBean extends HttpServlet
  5. implements EnvironmentCapable, EnvironmentAware {
  6. ... ...
  7. }
  8. public abstract class HttpServlet extends GenericServlet
  9. implements java.io.Serializable
  10. {
  11. ... ...
  12. }

  所以在这样一个web容器启动的时候会调用HttpServletBean的init方法,这个方法覆盖了GenericServlet中的init方法。让我我们来看看代码:

  1.    @Override
  2. public final void init() throws ServletException {
  3. if (logger.isDebugEnabled()) {
  4. logger.debug("Initializing servlet '" + getServletName() + "'");
  5. }
  6.  
  7. // Set bean properties from init parameters.
  8. try {
  9. PropertyValues pvs = new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties);
  10. BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
  11. ResourceLoader resourceLoader = new ServletContextResourceLoader(getServletContext());
  12. bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, getEnvironment()));
  13. initBeanWrapper(bw);
  14. bw.setPropertyValues(pvs, true);
  15. }
  16. catch (BeansException ex) {
  17. logger.error("Failed to set bean properties on servlet '" + getServletName() + "'", ex);
  18. throw ex;
  19. }
  20.  
  21. // Let subclasses do whatever initialization they like.
  22. initServletBean();
  23.  
  24. if (logger.isDebugEnabled()) {
  25. logger.debug("Servlet '" + getServletName() + "' configured successfully");
  26. }
  27. }

  该初始化方法的主要作用:将Servlet初始化参数(init-param)设置到该组件上(如contextAttribute、contextClass、namespace、contextConfigLocation),通过BeanWrapper简化设值过程,方便后续使用;提供给子类初始化扩展点,initServletBean(),该方法由FrameworkServlet覆盖。

  FrameworkServlet继承HttpServletBean,通过initServletBean()进行Web上下文初始化,该方法主要覆盖一下两件事情:初始化web上下文;提供给子类初始化扩展点。

  1.    @Override
  2. protected final void initServletBean() throws ServletException {
  3. getServletContext().log("Initializing Spring FrameworkServlet '" + getServletName() + "'");
  4. if (this.logger.isInfoEnabled()) {
  5. this.logger.info("FrameworkServlet '" + getServletName() + "': initialization started");
  6. }
  7. long startTime = System.currentTimeMillis();
  8.  
  9. try {
  10. this.webApplicationContext = initWebApplicationContext();
  11. initFrameworkServlet();
  12. }
  13. catch (ServletException ex) {
  14. this.logger.error("Context initialization failed", ex);
  15. throw ex;
  16. }
  17. catch (RuntimeException ex) {
  18. this.logger.error("Context initialization failed", ex);
  19. throw ex;
  20. }
  21.  
  22. if (this.logger.isInfoEnabled()) {
  23. long elapsedTime = System.currentTimeMillis() - startTime;
  24. this.logger.info("FrameworkServlet '" + getServletName() + "': initialization completed in " +
  25. elapsedTime + " ms");
  26. }
  27. }

  DispatcherServlet继承FrameworkServlet,并实现了onRefresh()方法提供一些前端控制器相关的配置。

  整个DispatcherServlet初始化的过程和做了些什么事情,具体主要做了如下两件事情:

  1、初始化Spring Web MVC使用的Web上下文,并且指定父容器为WebApplicationContext(ContextLoaderListener加载了的根上下文);

  2、初始化DispatcherServlet使用的策略,如HandlerMapping、HandlerAdapter等。

  onRefresh方法代码如下:

  1. @Override
  2. protected void onRefresh(ApplicationContext context) {
  3. initStrategies(context);
  4. }
  5.  
  6. /**
  7. * Initialize the strategy objects that this servlet uses.
  8. * <p>May be overridden in subclasses in order to initialize further strategy objects.
  9. */
  10. protected void initStrategies(ApplicationContext context) {
  11. initMultipartResolver(context);
  12. initLocaleResolver(context);
  13. initThemeResolver(context);
  14. initHandlerMappings(context);
  15. initHandlerAdapters(context);
  16. initHandlerExceptionResolvers(context);
  17. initRequestToViewNameTranslator(context);
  18. initViewResolvers(context);
  19. initFlashMapManager(context);
  20. }

总结

  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。

Spring的启动流程的更多相关文章

  1. Spring Boot启动流程分析

    引言 早在15年的时候就开始用spring boot进行开发了,然而一直就只是用用,并没有深入去了解spring boot是以什么原理怎样工作的,说来也惭愧.今天让我们从spring boot启动开始 ...

  2. Spring Boot启动流程详解(一)

    环境 本文基于Spring Boot版本1.3.3, 使用了spring-boot-starter-web. 配置完成后,编写了代码如下: @SpringBootApplication public ...

  3. Spring Boot启动流程详解

    注:本文转自http://zhaox.github.io/java/2016/03/22/spring-boot-start-flow 环境 本文基于Spring Boot版本1.3.3, 使用了sp ...

  4. Spring|IOC启动流程

    1.IOC启动流程 IOC的启动流程分为两个阶段,第一阶段是容器的启动阶段,第二阶段是Bean实例化阶段. 容器的启动阶段:加载配置信息,分析配置信息,其他 Bean实例化阶段:实例化对象,装配依赖, ...

  5. Spring MVC启动流程分析

    本文是Spring MVC系列博客的第一篇,后续会汇总成贴子. Spring MVC是Spring系列框架中使用频率最高的部分.不管是Spring Boot还是传统的Spring项目,只要是Web项目 ...

  6. Spring Boot -- 启动流程分析之ApplicationContext 中

    上一节我们已经分析到AbsractApplicationContext类refresh方法中的postProcessBeanFactory方法,在分析registerBeanPostProcessor ...

  7. Spring Boot(三):Spring Boot中的事件的使用 与Spring Boot启动流程(Event 事件 和 Listeners监听器)

    前言:在讲述内容之前 希望大家对设计模式有所了解 即使你学会了本片的内容 也不知道什么时候去使用 或者为什么要这样去用 观察者模式: 观察者模式是一种对象行为模式.它定义对象间的一种一对多的依赖关系, ...

  8. web中spring框架启动流程第一发

    web.xml中springmvc相关配置如下:<servlet> <servlet-name>springmvc</servlet-name> <servl ...

  9. Spring Boot启动流程

    基础准备 1,BeanPostProcessor:这个接口的作用在于对于新构造的实例可以做一些自定义的修改.比如如何构造.属性值的修改.构造器的选择等等 2,BeanFactoryPostProces ...

随机推荐

  1. 下了个pkg包的jenkins,的使用方法

    三.如何启动Jenkins1.最简单的方法是双击Jenkins的pkg包,一步一步点同意,默认8080端口2.使用命令行启动打开terminal,进入到war包所在目录,执行命令: java -jar ...

  2. .net framework 4.0 安装失败解决办法

    方法一 1.打开cmd命令窗口   运行net stop WuAuServ    停止更新服务 2.开始----运行------输入%windir% 3.找到SoftwareDistribution的 ...

  3. pch文件的添加

    想说试了好久一直报错找不到文件,解决方法如下: 依次是:./项目名/文件夹名称/pch文件名

  4. 解决报错Fatal error in launcher

    换电脑重装python,打算安装第三方库的时候出现错误: Fatal error in launcher 然而在网上搜到的大多数是解决 —— Fatal error in launcher: Unab ...

  5. 【从零开始搭建K8S】【第一篇】CentOS7.6离线安装Docker(手动安装以及基于yum本地源安装)

    下载CentOS7.6以及最小化安装CentOS7.6版本.由于CentOS属于开源软件,在国内也有很多的mirror站点可供下载,我选择的是华为站点进行下载:http://mirrors.huawe ...

  6. c++学习笔记_3

    前言:本笔记所对应的课程为中国大学mooc中北京大学的程序设计与算法(三)C++面向对象程序设计,主要供自己复习使用,且本笔记建立在会使用c和java的基础上,只针对与c和java的不同来写 类和对象 ...

  7. [Cometoj#3 B]棋盘_状压dp

    棋盘 题目链接:https://cometoj.com/contest/38/problem/B?problem_id=1535 数据范围:略. 题解: 因为行数特别小,所以$dp$的时候可以状压起来 ...

  8. [转帖]linux之sed用法

    linux之sed用法 https://www.cnblogs.com/dong008259/archive/2011/12/07/2279897.html docker images | awk ' ...

  9. class.forName 和 classLoader的区别

    Java中的Class.forName()和ClassLoader都可以用来对类进行加载.Class.forName()除了将类的.class文件加载到JVM中 还会对类进行解释,执行类中的stati ...

  10. mingw-w64 gcc std::thread 行为异常

    我用的 ming-w64 gcc 是通过 MSYS2 安装的,包名是 mingw-w64-x86_64-gcc,版本 9.2.0-2. 我发现 std::thread 行为异常. int main() ...