在Spring应用中创建全局获取ApplicationContext对象

package com.cggol.commons;

 

import org.springframework.beans.BeansException;

import org.springframework.context.ApplicationContext;

import org.springframework.context.ApplicationContextAware;

 

/**

* 通过此类获取Spring容器中,注册类的对象

* 使用此类时,请在Spring的配置文件中,配置该类

*

*/

 

public class ApplicationContextHelper implements ApplicationContextAware

{

        //以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候取出ApplicaitonContext

         private static ApplicationContext  APPLICATION_COUNT;

       

        /** * 取得存储在静态变量中的ApplicationContext.*/

         @Override

         public void setApplicationContext(ApplicationContext applicationContext) throws BeansException

        {

             ApplicationContextHelper.APPLICATION_COUNT   =    applicationContext;

        }

 

         public static <T>   T   getBean(String beanName,   Class<T> clazz)

        {

                  return APPLICATION_COUNT .getBean(beanName,clazz);

         }

      

          /** * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.*/

        public static Object getBean(String  beanName)

        {

                return  APPLICATION_COUNT .getBean(beanName);

         }

 

}

 

 

 

//用到该类时,在applicationContext.xml中引用此类 

<!-- 将Spring容器对象注入此类 -->

 <bean class=“引入该类路径”/>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值