加载WebApplicationContext的方式

  WebApplicationContext是ApplicationContext的子接口,纵观Spring框架的几种容器,BeanFactory作为顶级的接口,是所有IOC容器的最上层接口,顾名思义WebApplicationContext是依赖于Web容器的一个Spring的IOC容器。前提条件是web容器启动后这个容器才能启动。那么如何借助web容器来启动Spring web的上下文?

  第一种方式:我们可以通过org.springframework.web.context.ContextLoaderServlet;第二种式:org.springframework.web.context.ContextLoaderListener.

这两种方式有什么不同呢?listener完全是观察者的设计,仅仅执行的是监听的任务,而servlet的启动要稍微延迟一些,启动的前后顺序是有影像的。所以我认为listener更好用一些,实际开发中的框架配置中也是listener更多一些,这一点大家应该有所体会。

配置如下:

 <context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param> <listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

上面那一种是Spring Web容器放在classpath下的任何路径的配置,如果是放在web.xml约定的配置,则可以省略context-param的配置

通过查看ContextLoaderListener的源代码可以发现它的类的结构如下图所示:

通过上图可以发现ContextLoaderListener继承了ContextLoader类以及实现了ServletContextListener接口,ServletContextListener又实现了EvenListener接口,所以这个监听器具有事件监听的功能,并且是监听了web容器,web容器启动马上加载执行。ContextLoader感觉更像是执行加载web容器的一个小小的core组件,负责执行加载web容器的逻辑。下面重点来说一说这个。

public void contextInitialized(ServletContextEvent event) {
     //首先先获取ContextLoader对象
this.contextLoader = createContextLoader();
if (this.contextLoader == null) {
this.contextLoader = this;
}
     //通过servletContext对象去加载WebApplicationContext
this.contextLoader.initWebApplicationContext(event.getServletContext());
}

initWebApplicationContext的主要代码:

public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
     //去servlet容器中去寻找org.springframework.web.context.WebApplicationContext.root作为key的value,也就是webApplicationContext对象
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) {
configureAndRefreshWebApplicationContext((ConfigurableWebApplicationContext)this.context, servletContext);
}
       //将ApplicationContext放入ServletContext中,其key为<WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
       
       //将ApplicationContext放入ContextLoader的全局静态常量Map中,其中key为:Thread.currentThread().getContextClassLoader()即当前线程类加载器
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;
}
}

从上面的代码大家应该明白了Spring初始化之后,将ApplicationContext存到在了两个地方(servletContext中和currentContextPerThread中),那么是不是意味着我们可以通过两种方式取得ApplicationContext?

第一种获取方式:

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

这样确实可以获取,但是如果需要我们自己去这样获取的话,未免Spring也太low了吧?那样会辜负Spring作为web开发第一核心框架的地位的。话不多说,其实Spring已经给我们提供接口了:

在WebApplicationContextUtils类中有一个静态方法:

 public static WebApplicationContext getRequiredWebApplicationContext(ServletContext sc)
throws IllegalStateException { WebApplicationContext wac = getWebApplicationContext(sc);
if (wac == null) {
throw new IllegalStateException("No WebApplicationContext found: no ContextLoaderListener registered?");
}
return wac;
}
 public static WebApplicationContext getWebApplicationContext(ServletContext sc) {
return getWebApplicationContext(sc, WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
}

通过执行上面的方法可以获取WebApplicationContext对象。

第二种方法:

借用ApplicationContextAware,ApplicationContext的帮助类能够自动装载ApplicationContext,只要你将某个类实现这个接口,并将这个实现类在Spring配置文件中进行配置,Spring会自动帮你进行注入 ApplicationContext.ApplicationContextAware的代码结构如下:

 public interface ApplicationContextAware {  

         void setApplicationContext(ApplicationContext applicationContext) throws BeansException;  

 }  

就这一个接口。可以这样简单的实现一个ApplicationContextHelper类:

 public class ApplicationHelper implements ApplicationContextAware {  

     private ApplicationContext applicationContext; 

     public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
this.applicationContext = applicationContext;
} public ApplicationContext getApplicationContext(){
return this.applicationContext;
}
}

通过ApplicationHelper我们就可以获得咱们想要的AppilcationContext类了。

这是我对如何获取Spring Web上下文的一个理解。

获取WebApplicationContext的几种方式的更多相关文章

  1. spring 获取 WebApplicationContext的几种方法

    spring 获取 WebApplicationContext的几种方法 使用ContextLoader WebApplicationContext webApplicationContext = C ...

  2. 获取Type的三种方式

    using System;using UnityEngine; public class Type_Test : MonoBehaviour{    private void Awake()    { ...

  3. java动态获取WebService的两种方式(复杂参数类型)

    java动态获取WebService的两种方式(复杂参数类型) 第一种: @Override public OrderSearchListRes searchOrderList(Order_Fligh ...

  4. AngularJS中获取数据源的几种方式

    在AngularJS中,可以从$rootScope中获取数据源,也可以把获取数据的逻辑封装在service中,然后注入到app.run函数中,或者注入到controller中.本篇就来整理获取数据的几 ...

  5. java 获取时间戳的三种方式

      java 获取时间戳的三种方式 CreationTime--2018年7月13日16点29分 Author:Marydon 1.实现方式 方式一:推荐使用 System.currentTimeMi ...

  6. 【Struts2】Struts2获取session的三种方式

    1.Map<String,Object> map =  ActionContext.getContext().getSession(); 2.HttpSession session = S ...

  7. js获取时间戳的三种方式

      js获取时间戳的三种方式 CreateTime--2018年5月23日08:44:10 Author:Marydon // 方式一:推荐使用 var timestamp=new Date().ge ...

  8. Struts2(四.注册时检查用户名是否存在及Action获取数据的三种方式)

    一.功能 1.用户注册页面 <%@ page language="java" contentType="text/html; charset=UTF-8" ...

  9. HTTP获取信息的四种方式

    HTTP 从网络获取信息的四种方式 GET GET指代你在浏览器中输入网址,浏览网站时做的事.例如,我们使用 http://www.baidu.com 的时候,可以将GET想象成他说:"hi ...

随机推荐

  1. 数据库部分(MySql)_2

    分组查询 分组查询通常和聚合函数结合使用,查询条件中每个XXX就以XXX为分组的条件: 格式:每个A的平均B select avg(B) from 表名 group by A; having 在whe ...

  2. vuex 、store、state (转载)

    vuex  文档 https://vuex.vuejs.org/zh/guide/state.html

  3. Java_IO流_抽象类

    一.   概念 流动,从一端流向另一端,源头与目的地 以程序为中心,程序与 数组/文件/网络连接/数据库, 二.   io流分类 流向:输入流与输出流 数据 :字节楼:二进制,所有文件都可以操作,包括 ...

  4. python基础学习(四)if判断语句

    if判断语句的基本语法 在python中,if判断的格式如下: if 条件: 条件成立时,执行的语句 ...... 注意:代码的缩进要使用一个tab键或者四个空格(建议使用四个空格,tab和空格最好不 ...

  5. springboot整合netty(二)

    目录 前言 正文 代码 1. 新建一个springboot项目,在pom文件中添加netty依赖: 2.新建netty服务 3.netty调用所需的服务类 4 springboot启动类 5.测试 我 ...

  6. 汇编语言--微机CPU的指令系统(五)(位操作指令)

    (6) 位操作指令 1.位扫描指令(Bit Scan Instruction) 指令的格式:BSF/BSR Reg, Reg/Mem ;80386+ 受影响的标志位:ZF 位扫描指令是在第二个操作数中 ...

  7. PNG,GIF,JPG的区别及如何选

    GIF: 1:256色 2: 无损,编辑 保存时候,不会损失. 3:支持简单动画. 4:支持boolean透明,也就是要么完全透明,要么不透明 JPEG: 1:millions of colors 2 ...

  8. select2 插件编辑时设置默认值

    function htDate(selectCustomerId, val) { var customerId = selectCustomerId; var values = val; ajaxJs ...

  9. 洛谷P3235 [HNOI2014]江南乐(Multi-SG)

    题目描述 小A是一个名副其实的狂热的回合制游戏玩家.在获得了许多回合制游戏的世界级奖项之后,小A有一天突然想起了他小时候在江南玩过的一个回合制游戏. 游戏的规则是这样的,首先给定一个数F,然后游戏系统 ...

  10. BZOJ4804: 欧拉心算(莫比乌斯反演 线性筛)

    题意 求$$\sum_1^n \sum_1^n \phi(gcd(i, j))$$ $T \leqslant 5000, N \leqslant 10^7$ Sol 延用BZOJ4407的做法 化到最 ...