springmvc容器启动过程主要的核心类有DispatcherServlet、FrameworkServlet、HttpServletBean这三个类。图一是三个类的之间的关系, HttpServletBean、FrameworkServlet均为抽象类。DispatcherServlet是FrameworkServlet一个具体实现的子类,从DispatcherServlet的继承体系来看,DispatcherServlet本质是一个HttpServlet。所以我我们只有在web.xml中配置DispatcherServlet才能够启动SpringMVC,图二为DispatcherServlet的配置,通过该配置将所有以/结尾的http请求都交由该Servlet去处理
解析web.xml。tomcat启动时会解析项目中web.xml,解析出我们在web.xml中配置的Listener、Servlet、和Filter。
加载并实例化DispatcherServlet。如果DispatcherServlet的load-on-startup参数为正数时会直接加载该Servlet。加载完DispatcherServlet后会实例化一个对象(基于单例),并调用Servlet对象的init放法。
执行init方法。DispatcherServlet中并没有init方法,init是其父类HttpServletBean中的方法,init方法HttpServletBean中被定义为了final方法,其子类不能再重写该方法。在主要执行的内容有根据init-param配置设置Servlet对象的一些属性、执行initServletBean方法进行初始化ServletBean。以下代码为init方法的实现
public final void init() throws ServletException {
if (logger.isDebugEnabled()) {
logger.debug("Initializing servlet '" + getServletName() + "'");
}
// 使用init-param参数初始化ServletBean是的一些属性值.其中核心的参数为 contextConfigLocation,该参数值为SpringMVC配置文件的位置。
PropertyValues pvs = new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties);
if (!pvs.isEmpty()) {
try {
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
ResourceLoader resourceLoader = new ServletContextResourceLoader(getServletContext());
bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, getEnvironment()));
// initBeanWrapper方法是一个空方法,子类可以根据需要对ServleBean实例的其他属性进行初始化操作
initBeanWrapper(bw);
bw.setPropertyValues(pvs, true);
}
catch (BeansException ex) {
if (logger.isErrorEnabled()) {
logger.error("Failed to set bean properties on servlet '" + getServletName() + "'", ex);
}
throw ex;
}
}
// 初始化ServletBean,该方法也是空方法,FrameworkServlet类重写了该方法完成ServletBean的初始化操作
initServletBean();
if (logger.isDebugEnabled()) {
logger.debug("Servlet '" + getServletName() + "' configured successfully");
}
}
执行initServletBean方法。HttpServletBean中initServletBean为空方法,具体实现交由其子类FrameworkServlet实现并且该方法也是一个final方法,无法被子类重写。FrameworkServlet中的initServletBean方法主要的工作是初始化WebApplicationContext管理处理Http请求时要用到的一些Bean(HandlerMapping、Controller等),initFrameworkServlet是空方法,如果有需要可以在子类中重写方法。DispatcherServlet未重写该方法。下面代码是initServletBean的实现。
protected final void initServletBean() throws ServletException {
getServletContext().log("Initializing Spring FrameworkServlet '" + getServletName() + "'");
if (this.logger.isInfoEnabled()) {
this.logger.info("FrameworkServlet '" + getServletName() + "': initialization started");
}
long startTime = System.currentTimeMillis();
try {
//初始化一个WebApplicationContext,主要用来管理controller、handleMapping、ViewResolver等bean。
this.webApplicationContext = initWebApplicationContext();
initFrameworkServlet();
}
catch (ServletException ex) {
this.logger.error("Context initialization failed", ex);
throw ex;
}
catch (RuntimeException ex) {
this.logger.error("Context initialization failed", ex);
throw ex;
}
if (this.logger.isInfoEnabled()) {
long elapsedTime = System.currentTimeMillis() - startTime;
this.logger.info("FrameworkServlet '" + getServletName() + "': initialization completed in " +
elapsedTime + " ms");
}
}
执行initWebApplicationContext。该方法的主要作用是初始化一个SpringMVC容器,如果当前应用中已经有Spring容器就将SpringMVC容器进行关联。一般来讲在项目同时中使用Spring和SpringMVC,会加载两个容器一个主要用来管理业务逻辑相关的Bean,SpringMVC还会加载一个容器用来管理controller、handleMapping、ViewResolver等和处理Http请求相关的Bean。以下代码是initWebApplicationContext的实现:
protected WebApplicationContext initWebApplicationContext() {
// 获取当前应用上下文已有的Spring容器
WebApplicationContext rootContext =
WebApplicationContextUtils.getWebApplicationContext(getServletContext());
WebApplicationContext wac = null;
if (this.webApplicationContext != null) {
wac = this.webApplicationContext;
if (wac instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;
if (!cwac.isActive()) {
if (cwac.getParent() == null) {
// The context instance was injected without an explicit parent -> set
// the root application context (if any; may be null) as the parent
cwac.setParent(rootContext);
}
configureAndRefreshWebApplicationContext(cwac);
}
}
}
if (wac == null) {
//查找应用上下文中是否存在WebApplicationContext
wac = findWebApplicationContext();
}
if (wac == null) {
//以spring容器为父容器,创建SpringMVC的子容器
wac = createWebApplicationContext(rootContext);
}
if (!this.refreshEventReceived) {
//以当前SpringMVC容器,刷新Servlet的一些属性的内容,该方法实现在DispatchServlet中,主要作用刷新DispatchServlet的handleMapping、ViewResolver等处理策略。
onRefresh(wac);
}
if (this.publishContext) {
// 将当前SpringMVC容器和ServletContext的属性关联,属性名FrameworkServlet.CONTEXT.${servlet-name}
String attrName = getServletContextAttributeName();
getServletContext().setAttribute(attrName, wac);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Published WebApplicationContext of servlet '" + getServletName() +
"' as ServletContext attribute with name [" + attrName + "]");
}
}
return wac;
}
执行onRefresh。该方法主要有DispatcherServlet实现主要用来根据WebApplicationContext初始初始化一些自己要用的一些策略对象,如HandleMapping的策略对象,下面代码是oRefresh的实现:
protected void onRefresh(ApplicationContext context) {
//根据ApplicationContext中bean,初始化一些DispatcherServlet要使用的策略对象。
initStrategies(context);
}
至此SpringMVC容器就初始化完成,可以开始工作。
SpringMVC加载过程主要的四个个重要的方法init、initServletBean、initWebApplicationContext、onRefresh。整个加载流程是典型的模板方法应用,在父类init方法中定义了加载流程,并把相关的步骤延迟到子类中完成,分工明确。HttpServletBean负责根据init-param对Servlet的属性进行初始化,FrameworkServlet负责初始化WebApplicationContext,DispatcherServlet负责根据初初始化完成的WebApplicationContext初始化Servlet自身要用到的一些属性,这些属性主要有handlerMappings、handlerAdapters、handlerExceptionResolvers、viewResolvers、multipartResolver、localeResolver、。