获取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 ...
随机推荐
- [转]MySQL 表锁和行锁机制
本文转自:http://www.cnblogs.com/itdragon/p/8194622.html MySQL 表锁和行锁机制 行锁变表锁,是福还是坑?如果你不清楚MySQL加锁的原理,你会被它整 ...
- 12个非常有用的JavaScript技巧
在这篇文章中,我将分享12个非常有用的JavaScript技巧.这些技巧可以帮助你减少并优化代码. 1) 使用!!将变量转换成布尔类型 有时,我们需要检查一些变量是否存在,或者它是否具有有效值,从而将 ...
- jqgrid中的column的日期格式
---恢复内容开始--- {name:'StartDate',index:'StartDate', formatter:"date", formatoptions: {newfor ...
- myeclipse无法部署项目的解决
一.问题 myeclipse无法部署项目,点击这个部署按钮没有反应. 二.解决办法 1.找到myeclipse的工作空间,也就是启动时的那个项目保存的空间,我的是在D:\myeclipse_works ...
- 汇编语言--微机CPU的指令系统(五)(比较运算指令)
(7)比较运算指令 在程序中,我们要时常根据某个变量或表达式的取值去执行不同指令,从而使程序表现出有不同的功能.为了配合这样的操作,在CPU的指令系统中提供了各种不同的比较指令.通过这些比较指令的执行 ...
- Python模块之信号(signal)
在了解了Linux的信号基础之 后,Python标准库中的signal包就很容易学习和理解.signal包负责在Python程序内部处理信号,典型的操作包括预设信号处理函数,暂 停并等待信号,以及定时 ...
- iphone手机投屏在哪里 手机无线投屏电脑
Iphone是我们经常使用的一款手机,有时候经常需要将一些文件图片信息等投屏到电脑,那么iphone手机投屏在哪里?可以无线投屏到电脑吗?其实很简单,下面就分享下苹果手机投屏的具体方法给大家,希望对大 ...
- uni-app 子组件如何调用父组件的方法
1.在父组件methods中定义一个方法: changeType:function(type){ this.typeActive = type; alert(type); } 2.在父组件引用子组件时 ...
- Flutter 布局(四)- Baseline、FractionallySizedBox、IntrinsicHeight、IntrinsicWidth详解
本文主要介绍Flutter布局中的Baseline.FractionallySizedBox.IntrinsicHeight.IntrinsicWidth四种控件,详细介绍了其布局行为以及使用场景,并 ...
- (后端)解决code唯一码(java)简便方法
public String next() { long appBootTimes = systemVariableService.getAppBootTimes(); return Long.toSt ...