通过对SpringMVC启动过程的深入研究,期望掌握Java Web容器启动过程;掌握SpringMVC启动过程;了解SpringMVC的配置文件如何配置,为什么要这样配置;掌握SpringMVC是如何工作的;掌握Spring源码的设计和增强阅读源码的技巧。
目录
1.Web容器初始化过程
2.SpringMVC中web.
3.认识ServletContextListener
4.认识ContextLoaderListener
5.DispatcherServlet初始化(HttpServletBean • FrameworkServlet • DispatcherServlet)
6.ContextLoaderListener与DispatcherServlet关系
7.DispatcherServlet的设计
8.DispatcherServlet工作原理
一、Web容器初始化过程
上图展示了web容器初始化的过程,其官方文档给出了这样的描述:
When a web application is deployed into a container, the following steps must be performed, in this order, before the web application begins processing client requests.
Instantiate an instance of each event listener identified by a <listener> element in the deployment descriptor.
For instantiated listener instances that implement ServletContextListener, call the contextInitialized() method.
Instantiate an instance of each filter identified by a <filter> element in the deployment descriptor and call each filter instance's init() method.
Instantiate an instance of each servlet identified by a <servlet> element that includes a <load-on-startup> element in the order defined by the load-on-startup element values, and call each servlet instance's init() method.
二、SpringMVC中web.
上图是截取的web.
上图是源码中接口ServletContextListener的定义,可以看到在其注释中指明:servlet和Filter初始化前和销毁后,都会给实现了servletContextListener接口的**发出相应的通知。
上面是类ContextLoadListener的定义,它实现了上面的servletContextListener。这里用到了代理模式,简单的代理了ContextLoader类。ContextLoadListener类用来创建Spring application context,并且将application context注册到servletContext里面去。
结合上面的WEB容器启动的过程,以及接口ServletContextListener和类ContextLoadListener。我们知道:
在 Servlet API中有一个ServletContextListener接口,它能够监听ServletContext对象的生命周期,实际上就是监听Web应用的生命周期。当Servlet容器启动或终止Web应用时,会触发ServletContextEvent事件,该事件由ServletContextListener来处理。在ServletContextListener接口中定义了处理ServletContextEvent 事件的两个方法contextInitialized()和contextDestroyed()。
ContextLoaderListener**的作用就是启动Web容器时,自动装配ApplicationContext的配置信息。因为它实现了ServletContextListener这个接口,在web.
上面是initWebApplicationContext的过程,方法名称即是其含义。方法中首先创建了WebApplicationContext,配置并且刷新实例化整个SpringApplicationContext中的Bean。因此,如果我们的Bean配置出错的话,在容器启动的时候,会抛异常出来的。
综上,ContextLoaderListener类起着至关重要的作用。它读取web.
三、DispatchServlet初始化
在SpringMVC架构中,DispatchServlet初始化
原标题:SpringMVC启动过程详解
关键词:Spring