ApplicationContextAware使用

原文:https://blog.csdn.net/wwd0501/article/details/63682793     点击打开链接

   当一个类实现了这个接口(ApplicationContextAware)之后,这个类就可以方便获得ApplicationContext中的所有bean,可以调取spring容器中管理的各个bean。

1 . 加载spring配置文件,在web.xml加上以下的信息:

<listener >
         <listener - class >org.springframework.web.context.ContextLoaderListener < /listener - class >
  < /listener >


2.指明bean 配置文件的路径添加到web.xml:

<context -param >
         <param -name >contextConfigLocation < /param -name >
         <param -value >classpath :conf /app -context.xml < /param -value >
  < /context -param >

 

注意:<param-name>contextConfigLocation</param-name>是不能改变的。

 

3、方法类ApplicationContextHelper

方法类ApplicationContextHelper实现ApplicationContextAware接口:

创建静态成员ApplicationContext对象

重写实现方法setApplicationContext() 给ApplicationContext对象赋值

添加Object getBean()方法,由此凭id获取容器管理的bean

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;


@Service
public class ApplicationContextHelper implements ApplicationContextAware
{

    private static ApplicationContext applicationContext;

    public void setApplicationContext(ApplicationContext _applicationContext)
            throws BeansException
    {
        applicationContext = _applicationContext;
    }

    public static Object getBean(String beanName)
    {
        return applicationContext.getBean(beanName);
    }

}

4、ApplicationContextHelper类纳入spring进行管理

   加载Spring配置文件时,如果Spring配置文件中所定义的Bean类实现了ApplicationContextAware 接口,那么在加载Spring配置文件时,会自动调用ApplicationContextAware 接口中的

public void setApplicationContext(ApplicationContext context) throws BeansException方法,

获得ApplicationContext对象,ApplicationContext对象是由spring注入的前提必须在Spring配置文件中指定该类

方法:将方法类ApplicationContextHelper作为一个普通的bean在spring的配置文件中进行注册或者加上用@Service方式注册

<bean id = "ApplicationContextHelper"  class = "com.cqjk.timer.ApplicationContextHelper" / >


5.使用:

overallSituationService = (IOverallSituationService) ApplicationContextHelper.getBean("overallSituationService");
infoService = (IInfoService) ApplicationContextHelper.getBean("infoService");

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值