上次看了spring的加载流程,今天发现或多都忘记了,今天又看了一下,顺便总结一下:
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中出现了相同的元素,则按照在配置文件中出现的先后顺序来加载。