分析配置DispatcherServlet类时load-on-startup标签作用
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:application.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
SpringMVC中DispatcherServlet是该框架的核心,所有的请求处理及返回都要经过该Servlet,于是我们必须在web.xml里面配置该Servlet,大多时候我们在配置该Servlet的时候都会顺手配置一下:<load-on-startup>数值</load-on-startup>元素。起初就是以为加载DispatcherServlet的,我们来详细研究一下关于load-on-startup的作用及其过程。
作用:load-on-startup元素标记容器表示是否在启动的时候就加载这个servlet(实例化并调用其init()方法),而<load-on-startup>x</load-on-startup>中x的取值1,2,3,4,5代表的是优先级,而非启动延迟时间。
过程:
1、因为该servlet是实例化并调用init()方法的,我们先进入该类寻找init()方法

从该类中可看出其定义的几个resolver都是由final修饰,表示该属性一旦被初始化便不可改变,这里不可改变的意思对基本类型来说是其值不可变,而对对象属性来说其引用不可再变。
所以我们在配置这些的时候不能随意定值,必须和其一致,如下示例:
<!--application.xml中的multipartResolver的id是个定值,如果写错了就会报错-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:defaultEncoding="UTF-8" p:maxInMemorySize="1024000"></bean>
经查找并未在DispatcherServlet中找到init()方法,我们往上一级找其父类(FrameworkServlet)未果,再往上一级(HttpServletBean)通过查找在HttpServletBean中找到了该方法
/**
* Map config parameters onto bean properties of this servlet, and
* invoke subclass initialization.
* @throws ServletException if bean properties are invalid (or required
* properties are missing), or if subclass initialization fails.
*/
@Override
public final void init() throws ServletException {
if (logger.isDebugEnabled()) {
logger.debug("Initializing servlet '" + getServletName() + "'");
} // Set bean properties from init parameters.
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;
}
} // Let subclasses do whatever initialization they like.
initServletBean(); if (logger.isDebugEnabled()) {
logger.debug("Servlet '" + getServletName() + "' configured successfully");
}
}
由其介绍可知其作用大概是,map配置参数到这个servlet的bean属性,并调用子类初始化,其子类初始化的处理就在于initServletBean();的作用,我们去寻找此方法的来源
(HttpServletBean)中找到了,但是个空方法,我们往回继续找在(FrameworkServlet)中找到了
/**
* Overridden method of {@link HttpServletBean}, invoked after any bean properties
* have been set. Creates this servlet's WebApplicationContext.
*/
@Override
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 {
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()方法:
/**
* Initialize and publish the WebApplicationContext for this servlet.
* <p>Delegates to {@link #createWebApplicationContext} for actual creation
* of the context. Can be overridden in subclasses.
* @return the WebApplicationContext instance
* @see #FrameworkServlet(WebApplicationContext)
* @see #setContextClass
* @see #setContextConfigLocation
*/
protected WebApplicationContext initWebApplicationContext() {
WebApplicationContext rootContext =
WebApplicationContextUtils.getWebApplicationContext(getServletContext());
WebApplicationContext wac = null; if (this.webApplicationContext != null) {
// A context instance was injected at construction time -> use it
wac = this.webApplicationContext;
if (wac instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;
if (!cwac.isActive()) {
// The context has not yet been refreshed -> provide services such as
// setting the parent context, setting the application context id, etc
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) {
// No context instance was injected at construction time -> see if one
// has been registered in the servlet context. If one exists, it is assumed
// that the parent context (if any) has already been set and that the
// user has performed any initialization such as setting the context id
wac = findWebApplicationContext();
}
if (wac == null) {
// No context instance is defined for this servlet -> create a local one
wac = createWebApplicationContext(rootContext);
} if (!this.refreshEventReceived) {
// Either the context is not a ConfigurableApplicationContext with refresh
// support or the context injected at construction time had already been
// refreshed -> trigger initial onRefresh manually here.
onRefresh(wac);
} if (this.publishContext) {
// Publish the context as a servlet context attribute.
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;
}
整个过程就是为了给wac赋值,并返回该值,最后执行了onRefresh()方法:
@Override
protected void onRefresh(ApplicationContext context) {
initStrategies(context);
}
然后执行initStrategies方法:
/**
* Initialize the strategy objects that this servlet uses.
* <p>May be overridden in subclasses in order to initialize further strategy objects.
*/
protected void initStrategies(ApplicationContext context) { //用于处理上传请求。处理方法是将普通的request包装成MultipartHttpServletRequest,后者可以直接调用getFile方法获取File.
initMultipartResolver(context); //SpringMVC主要有两个地方用到了Locale:一是ViewResolver视图解析的时候;二是用到国际化资源或者主题的时候。
initLocaleResolver(context); //用于解析主题。SpringMVC中一个主题对应一个properties文件,里面存放着跟当前主题相关的所有资源、
//如图片、css样式等。SpringMVC的主题也支持国际化,
initThemeResolver(context); //用来查找Handler的。
initHandlerMappings(context); //从名字上看,它就是一个适配器。Servlet需要的处理方法的结构却是固定的,都是以request和response为参数的方法。
//如何让固定的Servlet处理方法调用灵活的Handler来进行处理呢?这就是HandlerAdapter要做的事情
initHandlerAdapters(context); //其它组件都是用来干活的。在干活的过程中难免会出现问题,出问题后怎么办呢?
//这就需要有一个专门的角色对异常情况进行处理,在SpringMVC中就是HandlerExceptionResolver。
initHandlerExceptionResolvers(context); //有的Handler处理完后并没有设置View也没有设置ViewName,这时就需要从request获取ViewName了,
//如何从request中获取ViewName就是RequestToViewNameTranslator要做的事情了。
initRequestToViewNameTranslator(context); //ViewResolver用来将String类型的视图名和Locale解析为View类型的视图。
//View是用来渲染页面的,也就是将程序返回的参数填入模板里,生成html(也可能是其它类型)文件。
initViewResolvers(context); //用来管理FlashMap的,FlashMap主要用在redirect重定向中传递参数。
initFlashMapManager(context);
}
至此就完成了整个初始化过程了。
分析配置DispatcherServlet类时load-on-startup标签作用的更多相关文章
- 精尽Spring Boot源码分析 - 配置加载
该系列文章是笔者在学习 Spring Boot 过程中总结下来的,里面涉及到相关源码,可能对读者不太友好,请结合我的源码注释 Spring Boot 源码分析 GitHub 地址 进行阅读 Sprin ...
- 当web项目没有配置<welcome-file>index_1.jsp</welcome-file>默认标签启动tomcat后默认访问的页面是什么呢?
当web项目没有配置index_1.jsp默认标签启动tomcat后默认访问的页面是什么呢? 结果我启动后居然默认打开了index.jsp页面 为什么呢?为什么会访问我的.indexjsp页面呢?不是 ...
- 01 - spring mvc 概述及配置DispatcherServlet
1.Spring mvc 基于model2实现,整体框架流程如(图片来自百度): ①web容器接收到http请求,若匹配DispatcherServlet的请求映射路径(web.xml),则容器会交给 ...
- spring in action学习笔记十五:配置DispatcherServlet和ContextLoaderListener的几种方式。
在spring in action中论述了:DispatcherServlet和ContextLoaderListener的关系,简言之就是DispatcherServlet是用于加载web层的组件的 ...
- springboot mvc自动配置(一)自动配置DispatcherServlet和DispatcherServletRegistry
所有文章 https://www.cnblogs.com/lay2017/p/11775787.html 正文 springboot的自动配置基于SPI机制,实现自动配置的核心要点就是添加一个自动配置 ...
- Spring MVC+Spring +Hibernate配置事务,但是事务不起作用
最近做项目,被一个问题烦恼了很久.使用Spring MVC+Spring +Hibernate开发项目,在使用注解配置事务管理,刚开始发现无论如何数据库都无法更新,但是可以从数据库查询到数据.怀疑是配 ...
- Eventlog Analyzer日志管理系统、日志分析工具、日志服务器的功能及作用
Eventlog Analyzer日志管理系统.日志分析工具.日志服务器的功能及作用 Eventlog Analyzer是用来分析和审计系统及事件日志的管理软件,能够对全网范围内的主机.服务器.网络设 ...
- [Tomcat 源码分析系列] (一) : Tomcat 启动脚本-startup.bat
概述 我们通常使用 Tomcat 中的 startup.bat 来启动 Tomcat. 但是这其中干了一些什么事呢? 大家都知道一个 Java 程序需要启动的话, 肯定需要 main 方法, 那么这个 ...
- web.xml配置DispatcherServlet
1. org.springframework.web.servlet.DispatcherServlet 所在jar包: <dependency> <groupId>org.s ...
随机推荐
- Mybatis 的分页插件 PageHelper
我用的版本是PageHelper-4.1.1.Mybatis-3.3.0 PageHelper 依赖于 jsqlparser-0.9.4.jar 使用方法: 1.根据Mybatis的版本下载对应版 ...
- TM1638控制
原理图图纸: 显示控制与读按键与寄存器的对应 驱动代码:码云:
- 安装多个xcode对homebrew影响
安装多个xcode,可能会导致无法识别默认使用哪个xcode的情况,这时候执行下列语句,设置默认xcode sudo xcode-select --switch /Applications/Xcode ...
- FYF的煎饼果子
利用等差数列公式就行了,可以考虑特判一下m >= n($ m, n \neq 1 $),这时一定输出“AIYAMAYA”. #include <iostream> using nam ...
- eclipse配置tomcat后修改server.xml文件(如编码等)无效问题
我们用eclipse配置好tomcat后,在处理中文乱码或是配置数据源时,我们要修改Tomcat下的server.xml等文件. 修改后重启Tomcat服务器时发现xml文件又被还原了. 因为Tomc ...
- 「NOI2001」食物链
传送门 Luogu 解题思路 带权并查集我不会啊 考虑种类并查集(扩展域并查集的一种). 开三倍空间,一倍维护本身,二倍维护猎物,三倍维护天敌,然后用并查集搞一搞就好了. 细节注意事项 咕咕咕 参考代 ...
- Python - 关于属性访问的优先级,属性访问顺序,python attributel lookup,类和实例访问属性的顺序
object.__getattribute__(self, name) 类中的数据描述符 object.__dict__.get(name) 自身属性字典 object.__class__.__dic ...
- Fluent_Python_Part2数据结构,02-array-seq,序列类型
1. 序列数据 例如字符串.列表.字节序列.元组.XML元素.数据库查询结果等,在Python中用统一的风格去处理.例如,迭代.切片.排序.拼接等. 2. 容器序列与扁平序列 容器序列:容器对象包含任 ...
- 从ES6到ES10的新特性万字大总结
介绍ECMAScript是一种由Ecma国际(前身为欧洲计算机制造商协会)在标准ECMA-262中定义的脚本语言规范.这种语言在万维网上应用广泛,它往往被称为JavaScript或JScript,但实 ...
- Python爬虫:urllib库的基本使用
请求网址获取网页代码 import urllib.request url = "http://www.baidu.com" response = urllib.request.ur ...