- web容器加载web.xml中的ContextLoaderListener
- 初始化spring容器
- 加载配置文件,创建bean
Web.xml
web容器为spring提供了宿主环境Servletcontext,启动时读取web.xml/包括ContextLoaderListener启动spring容器、DispathcherServlet springmvc分发器,
1 | <?xml version="1.0" encoding="UTF-8"?> |
web容器的初始化过程:
- web容器(如tomcat)读取web.xml, 读取文件中两个节点和
- 容器创建ServletContext,它是web的上下文,整个web项目都会用到它
- 读取context-param节点,它以 键值对的形式出现。将节点值转化为键值对,传给ServletContext
- 容器创建中的实例,创建监听器。监听器必须继承ServletContextListener
- 调用ServletContextListener的contextInitialized()方法,spring容器的创建和初始化就是在这个方法中
initWebApplicationContext
初始化spring容器,使用默认的配置文件,或者context-params中的配置contextConfigLocation
org.springframework.web.context.ContextLoader#initWebApplicationContext
1 | public WebApplicationContext initWebApplicationContext(ServletContext servletContext) { |
initWebApplicationContext()主要做三件事
- 创建WebApplicationContext,通过createWebApplicationContext()方法
- 加载spring配置文件,并创建beans。通过configureAndRefreshWebApplicationContext()方法
- 将spring容器context挂载到ServletContext 这个web容器上下文中。通过servletContext.setAttribute()方法。
createWebApplicationContext 创建spring容器
初始化root webAppLicationContext,采用默认配置或者自定义的class
1 | protected WebApplicationContext createWebApplicationContext(ServletContext sc) { |
configureAndRefreshWebApplicationContext 加载spring配置文件,创建beans
1 | protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) { |
1 | //读取配置文件、并创建和初始化beans |
参考文献
https://blog.csdn.net/u013510838/article/details/75066884
https://blog.csdn.net/moshenglv/article/details/53517343