spring启动加载流程

上次看了spring的加载流程,今天发现或多都忘记了,今天又看了一下,顺便总结一下:

标题spring的web项目启动:

1、首先web容器(比如Tomcat)会读取配置在web.xml中的监听器,从而启动spring容器。

<!--web项目中上下文初始化参数, name value的形式 -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>

<!--ContextLoaderListener,会通过它的监听启动spring容器-->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!--DispatherServlet,前端MVC核心,分发器,SpringMVC的核心-->
<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

1、web容器(如tomcat)读取web.xml, 创建ServletContext,它是web的上下文,整个web项目都会用到它。
2、读取context-param节点,它以 键值对的形式出现。将节点值转化为键值对,传给ServletContext。(默认的文件为/WEB-INF/applicationContext.xml)。
3、容器创建中的实例,创建监听器。监听器必须继承ServletContextListener 调用ServletContextListener的contextInitialized()方法,spring容器的创建和初始化就是在这个方法中。
4、在web容器初始化过程中,会创建节点的监听器,并调用它的contextInitialized()方法。这个方法中会完成spring容器的创建,初始化,以及beans的创建。(会调用以下方法)
initWebApplicationContext()主要做三件事

  • 创建WebApplicationContext,通过createWebApplicationContext()方法
    加载spring配置文件,并创建beans。
  • 通过configureAndRefreshWebApplicationContext()方法
  • 将spring容器context挂载到ServletContext
  • 这个web容器上下文中。通过servletContext.setAttribute()方法。
    createWebApplicationContext 创建spring容器
  • 获取WebApplicationContext实现类的class对象
  • 根据class对象创建实例对象
    configureAndRefreshWebApplicationContext加载spring配置文件,创建beans
    configureAndRefreshWebApplicationContext()这个方法会先读取web.xml中声明的contextConfigLocation元素,通过它找到spring配置文件。然后在refresh()方法中读取配置文件,并创建和初始化beans。所以重中之重还是refresh()方法

流程图

spring容器初始化的整个流程图如下
在这里插入图片描述
创建WebApplicationContext对象流程如下
在这里插入图片描述
读取XML配置文件,创建beans流程如下
在这里插入图片描述
转载:https://blog.csdn.net/u013510838/article/details/75066884
注:web.xml的加载顺序是:context-param-listener-filter-servlet。其中,如果web.xml中出现了相同的元素,则按照在配置文件中出现的先后顺序来加载。

  • 5
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值