zoukankan      html  css  js  c++  java
  • 获取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更多一些,这一点大家应该有所体会。

    配置如下:

    1 <context-param> 
    2 <param-name>contextConfigLocation</param-name> 
    3 <param-value>/WEB-INF/applicationContext.xml</param-value> 
    4 </context-param> 
    5 
    6 <listener> 
    7 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
    8 </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?

    第一种获取方式:

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

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

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

    1 public static WebApplicationContext getRequiredWebApplicationContext(ServletContext sc)
    2             throws IllegalStateException {
    3 
    4         WebApplicationContext wac = getWebApplicationContext(sc);
    5         if (wac == null) {
    6             throw new IllegalStateException("No WebApplicationContext found: no ContextLoaderListener registered?");
    7         }
    8         return wac;
    9     }
    1 public static WebApplicationContext getWebApplicationContext(ServletContext sc) {  
    2         return getWebApplicationContext(sc, WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);  
    3     }  

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

    第二种方法:

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

    1 public interface ApplicationContextAware {  
    2 
    3         void setApplicationContext(ApplicationContext applicationContext) throws BeansException;  
    4 
    5 }  

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

     1 public class ApplicationHelper implements ApplicationContextAware {  
     2 
     3 
     4     private ApplicationContext applicationContext; 
     5 
     6     public void setApplicationContext(ApplicationContext applicationContext)  
     7             throws BeansException {  
     8             this.applicationContext = applicationContext;  
     9     }  
    10 
    11 
    12     public  ApplicationContext getApplicationContext(){
    13         return this.applicationContext;  
    14     }  
    15 }  

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

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

  • 相关阅读:
    2558: 游起来吧!超妹!
    2554: 巨巨来袭
    2557: 不如来21玩一局?
    tortoisesvn 本项目的忽略项
    【C语言】随机数随机种子
    【leetcode】按奇偶排序数组
    【leetcode】按奇偶排序数组 II
    【leetcode】根据数字二进制下 1 的数目排序
    【leetcode】合并排序的数组
    【leetcode】稀疏数组搜索
  • 原文地址:https://www.cnblogs.com/yujiwei/p/7236753.html
Copyright © 2011-2022 走看看