加载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. 第一册:lesson sixty nine.

    原文: The car race. There is a car race near our town every year. In 1995 ,there was a very big race. ...

  2. 记录Newtonsoft.Json的日常用法

    最近在做一个使用基于.net mvc 实现前后台传输Json的实例.网上找了一些资料.发现在开发的时候,许多的数据交互都是以Json格式传输的.其中涉及序列化对象的使用的有DataContractJs ...

  3. JavaWeb学习日记----DTD

    DTD:文档类型定义,可以定义合法的XML文档构建模块.使用一系列的合法标签元素来定义文档的结构. 现有一个XML文档内容如下: <?xml version="1.0"?&g ...

  4. 继承、接口、static、abstract

    继承: 1.用extends来完成继承 2.子类可以继承父类全部的数据域但是只有部分的数据域对子类可见 3.在java中支持单继承 4.单继承和多继承的比较 (1)多继承比单继承能够更好的提高代码的复 ...

  5. EF中更新操作 ID自增但不是主键 ;根据ViewModel更新实体的部分属性

    //ID自增但不是主键的情况 public int Update_join<TEntity>(TEntity entity) where TEntity : class { dbconte ...

  6. mac svn的使用

    一.概述 在windows下,我们常常用TortoiseSVN管理svn代码.在mac下,自带svn客户端和服务器端功能. 二.服务端:创建代码仓库,用来存储客户端所上传的代码 (1)创建svn代码存 ...

  7. angularJs学习笔记-路由

    1.angular路由介绍 angular路由功能是一个纯前端的解决方案,与我们熟悉的后台路由不太一样. 后台路由,通过不同的 url 会路由到不同的控制器 (controller) 上,再渲染(re ...

  8. vue从入门到进阶:Class 与 Style 绑定(四)

    绑定 HTML Class 对象语法 ①.添加单个class: <div v-bind:class="{ active: isActive }"></div> ...

  9. CSS之IE浏览器的hasLayout,IE低版本的bug根源

    什么是hasLayout? hasLayout是IE特有的一个属性.很多的ie下的css bug都与其息息相关.在ie中,一个元素要么自己对自身的内容进行计算大小和组织,要么依赖于父元素来计算尺寸和组 ...

  10. C# 8.0的三个值得关注的新特性

    本文翻译自:https://dzone.com/articles/3-new-c-8-features-we-are-excited-about 转载请注明出自:葡萄城官网,葡萄城为开发者提供专业的开 ...