获取WebApplicationContext的几种方式
加载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的几种方式的更多相关文章
- spring 获取 WebApplicationContext的几种方法
spring 获取 WebApplicationContext的几种方法 使用ContextLoader WebApplicationContext webApplicationContext = C ...
- 获取Type的三种方式
using System;using UnityEngine; public class Type_Test : MonoBehaviour{ private void Awake() { ...
- java动态获取WebService的两种方式(复杂参数类型)
java动态获取WebService的两种方式(复杂参数类型) 第一种: @Override public OrderSearchListRes searchOrderList(Order_Fligh ...
- AngularJS中获取数据源的几种方式
在AngularJS中,可以从$rootScope中获取数据源,也可以把获取数据的逻辑封装在service中,然后注入到app.run函数中,或者注入到controller中.本篇就来整理获取数据的几 ...
- java 获取时间戳的三种方式
java 获取时间戳的三种方式 CreationTime--2018年7月13日16点29分 Author:Marydon 1.实现方式 方式一:推荐使用 System.currentTimeMi ...
- 【Struts2】Struts2获取session的三种方式
1.Map<String,Object> map = ActionContext.getContext().getSession(); 2.HttpSession session = S ...
- js获取时间戳的三种方式
js获取时间戳的三种方式 CreateTime--2018年5月23日08:44:10 Author:Marydon // 方式一:推荐使用 var timestamp=new Date().ge ...
- Struts2(四.注册时检查用户名是否存在及Action获取数据的三种方式)
一.功能 1.用户注册页面 <%@ page language="java" contentType="text/html; charset=UTF-8" ...
- HTTP获取信息的四种方式
HTTP 从网络获取信息的四种方式 GET GET指代你在浏览器中输入网址,浏览网站时做的事.例如,我们使用 http://www.baidu.com 的时候,可以将GET想象成他说:"hi ...
随机推荐
- 第一册:lesson eighty three.
原文:Going on holiday. A:Hello Sam, come in. B:Hi,Sam.We are having lunch. Do you want to have lunch w ...
- 【转载】PhpStudy修改网站根目录
phpStudy是一个PHP调试环境的程序集成包.该程序包集成最新的Apache+PHP+MySQL+phpMyAdmin+ZendOptimizer,一次性安装,无须配置即可使用,是非常方便.好用的 ...
- ABP适配Oracle全过程
一.背景 ABP的各类文档在网络上已经非常完善了,唯独缺少与oralce相关的资料,ABP官网也未给出一个较好的Oracle解决方案.正好最近在学习ABP相关知识,对ABP源码结构稍算熟悉,花了些 ...
- WCF SqlParameter序列化问题解决方案
博文 http://www.cnblogs.com/pan11jing/archive/2011/08/19/2051827.html 通过自定义类,再在WCF端转换的方式解决问题,之后出现了一个很小 ...
- php的依赖注入容器
这里接着上一篇 php依赖注入,直接贴出完整代码如下: <?php class C { public function doSomething() { echo __METHOD__, '我是C ...
- 计算机1&操作系统硬件
1.什么是编程语言? 语言是一种事物与另外一种事物沟通的表达方式 而编程则是人与计算机沟通的表达方式 2:什么是编程? 编程就是程序员用计算机能理解的的表达方式,把程序员想要表达的内容写到文件里, ...
- 如何创建.gitignore文件,忽略git不必要提交的文件
touch .gitignore 在项目目录里输入以上名利后,会自动生成一个文件 .gitignore,可在文件里写入忽略的文件名,例如 node_modules coverage .idea npm ...
- JAVA 多线程(3)
再讲线程安全: 一.脏读 脏读:在于读字,意在在读取实例变量时,实例变量有可能被另外一个线程更改了,导致获取到的数据出现异常. 在非线程安全的情况下,如果线程A与线程B 共同使用对象实例C中的方法me ...
- 搞清Image加载事件(onload)、加载状态(complete)后,实现图片的本地预览,并自适应于父元素内(完成)
onload与complete介绍 complete只是HTMLImageElement对象的一个属性,可以判断图片加载完成,不管图片是不是有缓存:而onload则是这个Image对象的load事件回 ...
- 28.Odoo产品分析 (四) – 工具板块(1) – 项目(1)
查看Odoo产品分析系列--目录 "项目管理"是一个用于管理你的项目,且将它们与其他应用关联起来的非常灵活的模块,他允许您的公司管理项目阶段,分配团队,甚至跟踪与项目相关的时间和工 ...