一、什么是DispatcherServlet
在整个SpringMVC框架中,DispatcherServlet处于核心位置,它负责协调和组织不同组件完成请求处理并返回响应工作。DispatcherServlet是SpringMVC统一的入口,所有的请求都通过它。
我们先看下DispatcherServlet的类图
可以看到DispatcherServlet本质上是一个Servlet,而我们知道Servlet的生命周期是init -> service -> destroy,下面我们看看DispatcherServlet的初始化过程,也就是init方法
二、DispatcherServlet的初始化过程
DispatcherServlet的init方法在其父类HttpServletBean里
//HttpServletBean
@Override
public final void init() throws ServletException {
// 这里是读取xml配置,不重要
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(bw);
bw.setPropertyValues(pvs, true);
}
catch (BeansException ex) {
if (logger.isErrorEnabled()) {
logger.error("Failed to set bean properties on servlet '" + getServletName() + "'", ex);
}
throw ex;
}
}
// 调用子类的实现方法
initServletBean();
}
跟着23行initServletBean进去,来到子类FrameworkServlet中
//FrameworkServlet
@Override
protected final void initServletBean() throws ServletException {
//打印一些日志
getServletContext().log("Initializing Spring " + getClass().getSimpleName() + " '" + getServletName() + "'");
if (logger.isInfoEnabled()) {
logger.info("Initializing Servlet '" + getServletName() + "'");
}
long startTime = System.currentTimeMillis();
try {
//重点是这个,初始化WebApplicationContext
//WebApplicationContext是SpringMVC的IOC容器
this.webApplicationContext = initWebApplicationContext();
initFrameworkServlet();
}
catch (ServletException | RuntimeException ex) {
logger.error("Context initialization failed", ex);
throw ex;
}
if (logger.isDebugEnabled()) {
String value = this.enableLoggingRequestDetails ?
"shown which may lead to unsafe logging of potentially sensitive data" :
"masked to prevent unsafe logging of potentially sensitive data";
logger.debug("enableLoggingRequestDetails='" + this.enableLoggingRequestDetails +
"': request parameters and headers will be " + value);
}
if (logger.isInfoEnabled()) {
logger.info("Completed initialization in " + (System.currentTimeMillis() - startTime) + " ms");
}
}
点击13行initWebApplicationContext进去
//FrameworkServlet
protected WebApplicationContext initWebApplicationContext() {
//获取WebApplicationContext,Spring容器
WebApplicationContext rootContext =
WebApplicationContextUtils.getWebApplicationContext(getServletContext());
WebApplicationContext wac = null;
if (this.webApplicationContext != null) {
// 如果WebApplicationContext不为空,说明该类在构造时已经将其注入
wac = this.webApplicationContext;
if (wac instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;
if (!cwac.isActive()) {
if (cwac.getParent() == null) {
//将Spring的容器设为SpringMVC容器的父容器
cwac.setParent(rootContext);
}
configureAndRefreshWebApplicationContext(cwac);
}
}
}
if (wac == null) {
//如果WebApplicationContext为空,则进行查找,能找到说明上下文已经在别处初始化
wac = findWebApplicationContext();
}
if (wac == null) {
//如果WebApplicationContext还是空,就以Spring的容器为父容器建一个新的
wac = createWebApplicationContext(rootContext);
}
if (!this.refreshEventReceived) {
synchronized (this.onRefreshMonitor) {
//模版方法,由子类DispatcherServlet实现
onRefresh(wac);
}
}
if (this.publishContext) {
//发布这个WebApplicationContext容器到ServletContext中.
String attrName = getServletContextAttributeName();
getServletContext().setAttribute(attrName, wac);
}
return wac;
}
点击34行onRefresh来到子类DispatcherServlet里
//DispatcherServlet
@Override
protected void onRefresh(ApplicationContext context) {
initStrategies(context);
}
//初始化SpringMVC的九大组件
protected void initStrategies(ApplicationContext context) {
//多文件上传组件
initMultipartResolver(context);
//多语言支持组件
initLocaleResolver(context);
//主题模板处理组件
initThemeResolver(context);
//URL映射组件
initHandlerMappings(context);
//业务逻辑适配组件
initHandlerAdapters(context);
//异常处理组件
initHandlerExceptionResolvers(context);
//视图名称提取组件
initRequestToViewNameTranslator(context);
//视图渲染组件
initViewResolvers(context);
//闪存管理组件
initFlashMapManager(context);
}
总结:
GenericServlet接收上下文对象,HttpServletBean给属性赋值,FrameworkServlet负责创建并初始化WebApplicationContext容器,最后DispatcherServlet初始化九大组件