`
flychao88
  • 浏览: 742302 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Spring ApplicationContextAware使用方法

 
阅读更多

       项目用到了ApplicationContextAware,通过它Spring容器会自动把上下文环境对象调用ApplicationContextAware接口中的setApplicationContext方法。

我们在ApplicationContextAware的实现类中,就可以通过这个上下文环境对象得到Spring容器中的Bean。

使用方法如下:

1.实现ApplicationContextAware接口:

  1. package com.bis.majian.practice.module.spring.util;  
  2.   
  3. import org.springframework.beans.BeansException;  
  4. import org.springframework.context.ApplicationContext;  
  5. import org.springframework.context.ApplicationContextAware;  
  6.   
  7. public class SpringContextHelper implements ApplicationContextAware {  
  8.     private static ApplicationContext context = null;  
  9.   
  10.     @Override  
  11.     public void setApplicationContext(ApplicationContext applicationContext)  
  12.             throws BeansException {  
  13.         this.context = applicationContext;  
  14.     }  
  15.       
  16.     public static Object getBean(String name){  
  17.         return context.getBean(name);  
  18.     }  
  19.       
  20. }  


2.在Spring的配置文件中配置这个类,Spring容器会在加载完Spring容器后把上下文对象调用这个对象中的setApplicationContext方法:

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="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.       
  12.     <bean id="springContextHelper" class="com.bis.majian.practice.module.spring.util.SpringContextHelper"></bean>  
  13.       
  14.     <context:component-scan base-package="com.bis.majian.practice.module.*" />  
  15. </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容器中的对象了。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics