前言:

  使用springMvc已经三年了,但是内部原来一直不太了解,看到ServletConetxt和ApplicationContext头就大,趁着这几天学习,正好学习下相关的知识。

  1.ServletContext

    首先我们说到ServletContext,ServletContext是一个Web应用的全局上下文,可以理解为整个Web应用的全局变量,项目中的所有方法皆可以获取ServletContext。

    说到ServletContext,就到说到所有web项目的web.xml,下面我们先贴出web.xml的一部分配置:

  <context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:log4j.properties</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>listener.SessionListener</listener-class>
</listener>
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
<filter>
<filter-name>sessionFilter</filter-name>
<filter-class>web.filter.SessionFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>sessionFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

  上面贴出的就是web.xml的部分配置,在这里我们首先讲解下web项目启动的加载顺序:

    以Tomcat举例,启动Tomcat之后,首先会加载web.xml文件:

      a)容器首先读取web.xml中的<context-param>的配置内容和<listener>标签中配置项;

      b)紧接着实例化ServletContext对象,并将<context-param>配置的内容转化为键值传递给ServletContext;

      c)创建<listener>配置的监听器的类实例,并且启动监听;

      d)随后调用listener的contextInitialized(ServletContextEvent args)方法,ServletContext = ServletContextEvent.getServletContext();

       此时你可以通过ServletContext获取context-param配置的内容并可以加以修改,此时Tomcat还没完全启动完成。

      e)后续加载配置的各类filter;

      f)最后加载servlet;

    最后的结论是:web.xml中配置项的加载顺序是context-param=>listener=>filter=>servlet,配置项的顺序并不会改变加载顺序,但是同类型的配置项会应该加载顺序,servlet中也可以通过load-on-startup来指定加载顺序。

  ServletContext中的属性所有的servlet皆可以使用ServletContext.

  2.ApplicationContext

  首先介绍下applicationContext,applicationContext是spring的BeanFactory的实现类:

  

  ApplicationContext接口的继承关系如上面的截图,ApplicationContext是如何产生的呢,这里我们看之前的web.xml中的

  <listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

  继承关系如左图

  我们看看是如何初始化的

  

public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {
throw new IllegalStateException(
"Cannot initialize context because there is already a root application context present - " +
"check whether you have multiple ContextLoader* definitions in your web.xml!");
} Log logger = LogFactory.getLog(ContextLoader.class);
servletContext.log("Initializing Spring root WebApplicationContext");
if (logger.isInfoEnabled()) {
logger.info("Root WebApplicationContext: initialization started");
}
long startTime = System.currentTimeMillis(); try {
// Store context in local instance variable, to guarantee that
// it is available on ServletContext shutdown.
if (this.context == null) {
this.context = createWebApplicationContext(servletContext);
}
if (this.context instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
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 ->
// determine parent for root web application context, if any.
ApplicationContext parent = loadParentContext(servletContext);
cwac.setParent(parent);
}
configureAndRefreshWebApplicationContext(cwac, servletContext);
}
}
servletContext.setAttribute(c, this.context); ClassLoader ccl = Thread.currentThread().getContextClassLoader();
if (ccl == ContextLoader.class.getClassLoader()) {
currentContext = this.context;
}
else if (ccl != null) {
currentContextPerThread.put(ccl, this.context);
} if (logger.isDebugEnabled()) {
logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" +
WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]");
}
if (logger.isInfoEnabled()) {
long elapsedTime = System.currentTimeMillis() - startTime;
logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms");
} return this.context;
}
catch (RuntimeException ex) {
logger.error("Context initialization failed", ex);
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
throw ex;
}
catch (Error err) {
logger.error("Context initialization failed", err);
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err);
throw err;
}
}

  代码中加粗的部分就是讲WebApplicationContext以WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE为key保存到ServletContext中,所以我们在需要获取时,可以根据request.getSession().

  getAttribute("WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE")来获取WebApplicationContext.

  所以WebApplicationContext依赖于ServletContext,ApplicationContext存储了Spring中所有的Bean,

  但是我们常规的Springmvc项目一般除了applicationContext.xml之外还有springmvc.xml,两个配置文件会对应两个ApplicationContext,springmvc的ApplicationContext中可以调用applicationContext.xml的ApplciationContext。

  3.获取WebApplication的几种方式

    a)request.getSession().getServletContext().getAttribute("org.springframework.web.context.WebApplicationContext.ROOT")

    b)实现ApplicationContextAware接口

      

 public interface ApplicationContextAware {  

         void setApplicationContext(ApplicationContext applicationContext) throws BeansException;  

}  

 
分类: Java
 
好文要顶 关注我 收藏该文  

SpringMvc项目加载顺序及上下文小结的更多相关文章

  1. CSS样式表、JS脚本加载顺序与SpringMVC在URL路径中传参数与SpringMVC 拦截器

    CSS样式表和JS脚本加载顺序 Css样式表文件要在<head>中先加载,这样网页显示时可以第一次就渲染出正确的布局和样式,网页就不会闪烁,或跳变 JS脚本尽可能放在<body> ...

  2. java web.xml被文件加载过程及加载顺序小结

    web.xml加载过程(步骤): 1.启动WEB项目的时候,容器(如:Tomcat)会去读它的配置文件web.xml.读两个节点: <listener></listener> ...

  3. java web项目启动加载顺序

    转载:https://www.cnblogs.com/writeLessDoMore/p/6935524.html web.xml加载过程(步骤):       1.启动WEB项目的时候,容器(如:T ...

  4. 上下文ac获取为null,SpringContextUtil配置位置,以及各配置xml的加载顺序有讲究

    发现一个有趣的现象,一般job都会在执行前去初始化一次ac,而任务监视器SupervisorQueueJob不会,因此启动时初始化ac为null,SupervisorQueueJob会始终无法获取上下 ...

  5. java web项目中classes文件夹下的class和WEB-INF/lib中jar里的class文件加载顺序

    如果是发布到weblogic的话,可以在WebContent\WEB-INF\weblogic.xml里面配置.参考配置如下:<?xml version="1.0" enco ...

  6. web.xml加载顺序

    一 1.启动一个WEB项目的时候,WEB容器会去读取它的配置文件web.xml,读取<listener>和<context-param>两个结点. 2.紧急着,容创建一个Ser ...

  7. web.xml文件加载顺序

    1.启动一个WEB项目的时候,WEB容器会去读取它的配置文件web.xml,读取<listener>和<context-param>两个结点. 2.紧急着,容创建一个Servl ...

  8. web.xml 中的listener、 filter、servlet 加载顺序及其详解

    在项目中总会遇到一些关于加载的优先级问题,近期也同样遇到过类似的,所以自己查找资料总结了下,下面有些是转载其他人的,毕竟人家写的不错,自己也就不重复造轮子了,只是略加点了自己的修饰. 首先可以肯定的是 ...

  9. 详解web.xml中元素的加载顺序

    一.背景 最近在项目中遇到了启动时出现加载service注解注入失败的问题,后来经过不懈努力发现了是因为web.xml配置文件中的元素加载顺序导致的,那么就抽空研究了以下tomcat在启动时web.x ...

随机推荐

  1. HDU-1423-Greatest Common Increasing Subsequence-最长公共上升子序列【模版】

    This is a problem from ZOJ 2432.To make it easyer,you just need output the length of the subsequence ...

  2. 根据Cron表达式,通过Spring自带的CronSequenceGenerator类获取下次执行时间

    Cron表达式通常用于执行一些定时任务,在本篇文章中,暂时不会记录如何根据Cron表达式来执行一些定时任务.本章主要的目的是根据Cron表达式,通过Spring自带的CronSequenceGener ...

  3. PAT甲级——A1121 Damn Single【25】

    "Damn Single (单身狗)" is the Chinese nickname for someone who is being single. You are suppo ...

  4. DNS配置-BIND安装配置全过程

    下载地址:ftp://ftp.isc.org/isc/ 下载bind,我下载的是bind-9.11.13.tar.gz 我下载的文件放在/root目录下进入目录解压缩 [root@localhost ...

  5. 牛客暑期第六场G /// 树形DP 最大流最小割定理

    题目大意: 输入t,t个测试用例 每个测试用例输入n 接下来n行 输入u,v,w,树的无向边u点到v点权重为w 求任意两点间的最大流的总和 1.最大流最小割定理 即最大流等于最小割 2.无向树上的任意 ...

  6. 解决asp.net web api时间datetime自动带上带上的T和毫秒的问题

    今天用asp.net web api写微信小程序的接口时遇到一个问题. 返回的model中的datetime类型的字段自动转换成了“2014-11-08T01:50:06:234”这样的字符串,带上的 ...

  7. 执行sql查询,并查看语句执行花费时间

    declare @d datetimeset @d=getdate() select * from A PRINT '[语句执行花费时间(毫秒)]'+LTRIM(datediff(ms,@d,getd ...

  8. 解决在Spring整合Hibernate配置tx事务管理器出现错误的问题

    问题描述: Error occured processing XML 'org/aopalliance/intercept/MethodInterceptor'. See Error Log for ...

  9. BZOJ1597: [Usaco2008 Mar]土地购买——斜率优化

    题目大意: 将$n$个长方形分成若干部分,每一部分的花费为部分中长方形的$max_长*max_宽$(不是$max_{长*宽}$),求最小花费 思路: 首先,可以被其他长方形包含的长方形可以删去 然后我 ...

  10. ssm框架,出现xxx不能加载,或者bean不能加载时的解决方案之一

    有可能是你在项目的mapper.xml文件中添加了本项目没有的实体类, 你把日志中找不到的最后一个实体类全项目搜索下,改成本项目可以引用的即可