Spring Web Application Context加载流程
前言
最近打算花点时间好好看看spring的源码,然而现在spring的源码经过迭代的版本太多了,比较庞大,看起来比较累,所以准备从最初的版本(interface21)开始入手,仅用于学习,理解其设计思想,后续慢慢研究其每次版本变更的内容。。。
先从interface21的一个典型web工程例子看起,宠物诊所 - petclinic,因为该工程基本涵盖了spring的apo、ioc、jdbc、web mvc、事务、国际化、主题切换、参数校验等主要功能。。。
继上一篇,了解完contextloaderlistener(加载spring web application context)的流程后,看看spring mvc的关键控制器 - dispatcherservlet初始化流程是如何的~~~~~~~
对应的web.xml配置
<servlet> <servlet-name>petclinic</servlet-name> <servlet-class>com.interface21.web.servlet.dispatcherservlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>petclinic</servlet-name> <url-pattern>*.htm</url-pattern> </servlet-mapping>
这里有一个地方需要注意下,load-on-startup的配置,关于该servlet参数的含义,可以先看下web-app_2_3.dtd文件中的解释,如下,大致意思就是,如果没配置load-on-startup或该值为负数,则servlet容器可以*选择什么时候加载该servlet(实例化并执行servlet的init方法),如果为0或正数,则必须在容器启动时加载servlet并执行其init方法,且数值越小的servlet优先加载,回过头看我们的dispatcherservlet,由于load-on-startup配置成1,所以会在启动的时候,执行init方法,即本文要关注的dispatcherservlet初始化流程:
<!-- the load-on-startup element indicates that this servlet should be loaded (instantiated and have its init() called) on the startup of the web application. the optional contents of these element must be an integer indicating the order in which the servlet should be loaded. if the value is a negative integer, or the element is not present, the container is free to load the servlet whenever it chooses. if the value is a positive integer or 0, the container must load and initialize the servlet as the application is deployed. the container must guarantee that servlets marked with lower integers are loaded before servlets marked with higher integers. the container may choose the order of loading of servlets with the same load-on-start-up value. used in: servlet -->
执行时序图(看不清的话可以点击查看原图)
时序图中的各个步骤简要分析
执行的入口在httpservletbean类的init方法,由于dispatcherservlet的load-on-startup参数配置成1,所以在servlet容器(tomcat)启动时,会自动调用该servlet的init方法。
步骤描述:
- 首先,执行dispatcherservlet的父类httpservletbean的init方法;
public final void init() throws servletexception { this.identifier = "servlet with name '" + getservletconfig().getservletname() + "' "; logger.info(getidentifier() + "entering init..."); // set bean properties try { propertyvalues pvs = new servletconfigpropertyvalues(getservletconfig(), requiredproperties); beanwrapper bw = new beanwrapperimpl(this); bw.setpropertyvalues(pvs); logger.debug(getidentifier() + "properties bound ok"); // let subclasses do whatever initialization they like initservletbean(); logger.info(getidentifier() + "configured successfully"); } catch (beansexception ex) { string mesg = getidentifier() + ": error setting properties from servletconfig"; logger.error(mesg, ex); throw new servletexception(mesg, ex); } catch (throwable t) { // let subclasses throw unchecked exceptions string mesg = getidentifier() + ": initialization error"; logger.error(mesg, t); throw new servletexception(mesg, t); } }
- 获取servlet的初始化参数,创建beanwrapperimpl 实例,设置属性值;
- 执行httpservletbean的子类frameworkservlet的initservletbean方法;
protected final void initservletbean() throws servletexception { long starttime = system.currenttimemillis(); logger.info("framework servlet '" + getservletname() + "' init"); this.webapplicationcontext = createwebapplicationcontext(); initframeworkservlet(); long elapsedtime = system.currenttimemillis() - starttime; logger.info("framework servlet '" + getservletname() + "' init completed in " + elapsedtime + " ms"); }
- 调用frameworkservlet的createwebapplicationcontext方法。
private webapplicationcontext createwebapplicationcontext() throws servletexception { getservletcontext().log("loading webapplicationcontext for servlet '" + getservletname() + "'"); servletcontext sc = getservletconfig().getservletcontext(); webapplicationcontext parent = webapplicationcontextutils.getwebapplicationcontext(sc); string namespace = getnamespace(); webapplicationcontext waca = (this.contextclass != null) ? instantiatecustomwebapplicationcontext(this.contextclass, parent, namespace) : new xmlwebapplicationcontext(parent, namespace); logger.info("loading webapplicationcontext for servlet '" + getservletname() + "': using context class '" + waca.getclass().getname() + "'"); waca.setservletcontext(sc); if (this.publishcontext) { // publish the context as a servlet context attribute string attname = getservletcontextattributename(); sc.setattribute(attname, waca); logger.info("bound context of servlet '" + getservletname() + "' in global servletcontext with name '" + attname + "'"); } return waca; }
- 进入createwebapplicationcontext方法,从servletcontext的属性中获取webapplicationcontext,该上下文是由contextloaderlistener加载的
- 创建子上下文xmlwebapplicationcontext,其父上下文为之前contextloaderlistener加载的webapplicationcontext,关于这两个上下文的关系,及负责加载的内容,可参考这张图,图片来源()
- 执行子上下文xmlwebapplicationcontext的waca.setservletcontext方法,去加载petclinic-servlet.xml配置文件(国际化,主题,handlermapping、handleradapter、视图解析等相关配置),关于webapplicationcontext上下文的加载流程,可参考上一篇(spring web application context加载流程),流程都是相同的;
- 将该子上下文设置到servletcontext属性中
- 进入dispatcherservlet类的initframeworkservlet方法,主要执行一些初始化工作
protected void initframeworkservlet() throws servletexception { initlocaleresolver(); initthemeresolver(); inithandlermappings(); inithandleradapters(); initviewresolver(); }
- 国际化相关:执行initlocaleresolver方法,从上下文中获取localeresolver bean,没有则使用默认acceptheaderlocaleresolver
private void initlocaleresolver() throws servletexception { try { this.localeresolver = (localeresolver) getwebapplicationcontext().getbean(locale_resolver_bean_name); logger.info("loaded locale resolver [" + this.localeresolver + "]"); } catch (nosuchbeandefinitionexception ex) { // we need to use the default this.localeresolver = new acceptheaderlocaleresolver(); logger.info("unable to locate locale resolver with name '" + locale_resolver_bean_name + "': using default [" + this.localeresolver + "]"); } catch (beansexception ex) { // we tried and failed to load the localeresolver specified by a bean throw new servletexception("fatal error loading locale resolver with name '" + locale_resolver_bean_name + "': using default", ex); } }
- 主题相关:执行initthemeresolver方法,从上下文中获取themeresolver bean,没有则使用默认fixedthemeresolver
private void initthemeresolver() throws servletexception { try { this.themeresolver = (themeresolver) getwebapplicationcontext().getbean(theme_resolver_bean_name); logger.info("loaded theme resolver [" + this.themeresolver + "]"); } catch (nosuchbeandefinitionexception ex) { // we need to use the default this.themeresolver = new fixedthemeresolver(); logger.info("unable to locate theme resolver with name '" + theme_resolver_bean_name + "': using default [" + this.themeresolver + "]"); } catch (beansexception ex) { // we tried and failed to load the themeresolver specified by a bean throw new servletexception("fatal error loading theme resolver with name '" + theme_resolver_bean_name + "': using default", ex); } }
- 执行inithandlermappings方法,从上下文中获取handlermapping类型的bean,没有则使用默认beannameurlhandlermapping
private void inithandlermappings() throws servletexception { this.handlermappings = new arraylist(); // find all handlermappings in the applicationcontext string[] hms = getwebapplicationcontext().getbeandefinitionnames(handlermapping.class); for (int i = 0; i < hms.length; i++) { inithandlermapping(hms[i]); logger.info("loaded handler mapping [" + hms[i] + "]"); } // ensure we have at least one handlermapping, by registering // a default handlermapping if no other mappings are found. if (this.handlermappings.isempty()) { initdefaulthandlermapping(); logger.info("no handlermappings found in servlet '" + getservletname() + "': using default"); } else { // we keep handlermappings in sorted order collections.sort(this.handlermappings, new ordercomparator()); } }
private void initdefaulthandlermapping() throws servletexception { try { handlermapping hm = new beannameurlhandlermapping(); hm.setapplicationcontext(getwebapplicationcontext()); this.handlermappings.add(hm); } catch (applicationcontextexception ex) { throw new servletexception("error initializing default handlermapping: " + ex.getmessage(), ex); } }
- 执行inithandleradapters方法,从上下文中获取handleradapter类型的bean,没有则使用默认simplecontrollerhandleradapter
private void inithandleradapters() throws servletexception { this.handleradapters = new arraylist(); string[] has = getwebapplicationcontext().getbeandefinitionnames(handleradapter.class); for (int i = 0; i < has.length; i++) { inithandleradapter(has[i]); logger.info("loaded handler adapter [" + has[i] + "]"); } // ensure we have at least one handleradapter, by registering // a default handleradapter if no other adapters are found. if (this.handleradapters.isempty()) { initdefaulthandleradapter(); logger.info("no handleradapters found in servlet '" + getservletname() + "': using default"); } else { // we keep handleradapters in sorted order collections.sort(this.handleradapters, new ordercomparator()); } }
private void initdefaulthandleradapter() throws servletexception { try { handleradapter ha = new simplecontrollerhandleradapter(); ha.setapplicationcontext(getwebapplicationcontext()); this.handleradapters.add(ha); } catch (applicationcontextexception ex) { throw new servletexception("error initializing default handleradapter: " + ex.getmessage(), ex); } }
- 执行initviewresolver方法,从上下文中获取viewresolver bean,没有则使用默认internalresourceviewresolver
private void initviewresolver() throws servletexception { try { this.viewresolver = (viewresolver) getwebapplicationcontext().getbean(view_resolver_bean_name); logger.info("loaded view resolver [" + viewresolver + "]"); } catch (nosuchbeandefinitionexception ex) { // we need to use the default this.viewresolver = new internalresourceviewresolver(); try { this.viewresolver.setapplicationcontext(getwebapplicationcontext()); } catch (applicationcontextexception ex2) { throw new servletexception("fatal error initializing default viewresolver"); } logger.info("unable to locate view resolver with name '" + view_resolver_bean_name + "': using default [" + this.viewresolver + "]"); } catch (beansexception ex) { // we tried and failed to load the viewresolver specified by a bean throw new servletexception("fatal error loading view resolver: bean with name '" + view_resolver_bean_name + "' is required in servlet '" + getservletname() + "': using default", ex); } }
- 返回到frameworkservlet类
- 返回到httpservletbean类
- servlet的init方法执行完毕
另外可以关注下该servlet的销毁方法,类似的,也是执行一些资源销毁等操作,销毁工厂创建的单例bean对象,发布contextclosedevent事件等;
public void destroy() { getservletcontext().log("closing webapplicationcontext for servlet '" + getservletname() + "'"); getwebapplicationcontext().close(); }
public void close() { logger.info("closing application context [" + getdisplayname() + "]"); // destroy all cached singletons in this context, // invoking disposablebean.destroy and/or "destroy-method" getbeanfactory().destroysingletons(); // publish respective event publishevent(new contextclosedevent(this)); }
interface21代码参考
推荐阅读
-
Spring Web Application Context加载流程
-
Error configuring application listener of class org.springframework.web.context.
-
spring-mvc.xml 和 application-context.xml的配置与深入理解
-
Spring Refresh Application Context
-
SpringBoot加载web项目流程源码解析
-
解析spring加载bean流程的方法
-
Spring Bean的循环依赖 The dependencies of some of the beans in the application context form a cycle
-
Spring Security过滤器链加载执行流程源码解析
-
application context not configured for this file于spring框架使用中的原因
-
Java Web 摘录-Spring和Hibernate动态建表及动态加载映射文件