1. 程式人生 > >通過ApplicationContextAware載入Spring上下文環境

通過ApplicationContextAware載入Spring上下文環境

在程式中每一次使用new ClassPathXmlApplicationContext時都會重新裝載配置檔案並例項化上下文bean。此時如果某些執行緒類也配置在該檔案中,那麼會造成做相同工作的執行緒被啟動多次(包括web容器初始化時啟動的以及new ClasspathXmlApplicationContext時啟動的執行緒)。為了避免這種情況就需要用到ApplicationContextAware,通過它Spring容器會自動呼叫ApplicationContextAware介面中的setApplicationContext方法將把上下文環境物件注入進去

我們在ApplicationContextAware的實現類中,就可以通過這個上下文環境物件得到Spring容器中的Bean。

具體如下:

1.實現ApplicationContextAware介面:

  1. package com.bis.majian.practice.module.spring.util;  
  2. import org.springframework.beans.BeansException;  
  3. import org.springframework.context.ApplicationContext;  
  4. import org.springframework.context.ApplicationContextAware;  
  5. publicclass SpringContextHelper implements
     ApplicationContextAware {  
  6.     privatestatic ApplicationContext context = null;  
  7.     @Override
  8.     publicvoid setApplicationContext(ApplicationContext applicationContext)  
  9.             throws BeansException {  
  10.         this.context = applicationContext;  
  11.     }  
  12.     publicstatic Object getBean(String name){  
  13.         return context.getBean(name);  
  14.     }  
  15. }  

2.在Spring的配置檔案中配置這個類,Spring容器會在載入完Spring容器後把上下文物件呼叫這個物件中的setApplicationContext方法:

  1. <?xmlversion="1.0"encoding="UTF-8"?>
  2. <beansxmlns="http://www.springframework.org/schema/beans"
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:tx="http://www.springframework.org/schema/tx"
  4.     xmlns:context="http://www.springframework.org/schema/context"
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans   
  6.     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
  7.     http://www.springframework.org/schema/tx   
  8.     http://www.springframework.org/schema/tx/spring-tx-3.0.xsd   
  9.     http://www.springframework.org/schema/context   
  10.     http://www.springframework.org/schema/context/spring-context-3.0.xsd" default-autowire="byName">
  11.     <beanid="springContextHelper"class="com.bis.majian.practice.module.spring.util.SpringContextHelper"></bean>
  12.     <context:component-scanbase-package="com.bis.majian.practice.module.*"/>
  13. </beans>

3.在web專案中的web.xml中配置載入Spring容器的Listener:

  1. <!-- 初始化Spring容器,讓Spring容器隨Web應用的啟動而自動啟動 -->
  2.     <listener>
  3.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  4.     </listener>

4.在專案中即可通過這個SpringContextHelper呼叫getBean()方法得到Spring容器中的物件了。