Spring中ApplicationContextAware接口的使用

一、这个接口有什么用?

当一个类实现了这个接口(ApplicationContextAware)之后,这个类就可以方便获得ApplicationContext中的所有bean。换句话说,就是这个类可以直接获取spring配置文件中,所有有引用到的bean对象。


二、怎么使用这个接口?

例如我有一个方法类UserUtil,这个方法类中需要使用到的ApplicationContext中的某个bean(appService)。

1、因为Spring要建立属于自己的容器,就必须要加载自己的配置文件。则需要注册ContextLoaderListener或者这个类的子类。

web.xml配置加上:

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

当然,这样子的话只会读取默认路径下的application.xml配置文件的。

需要在web.xml中添加如下信息,例如:

 <!--默认配置-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:application.xml</param-value>
    </context-param>
如果需要读取特定路径下的配置文件。需要在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>是不能改变的。

2、方法类UserUtil的处理

(1)实现ApplicationContextAware接口:

public class UserUtil implements ApplicationContextAware

(2)为方法类UserUtil增加一个静态的成员ApplicationContext类型的对象。以后方法类AppUtil获取ApplicationContext,就是通过读取这个成员变量的。具体如下所示:
private ApplicationContext appContext;

实现ApplicationContextAware接口的默认方法:

public void setApplicationContext(ApplicationContext paramApplicationContext) throws BeansException{
    appContext = paramApplicationContext;
}

(3)在spring的配置文件中,注册方法类UserUtil

严格上来说,方法类UserUtil是一个bean,而且从步骤(2)中我们不难发现,之所以方法类UserUtil能够灵活自如地获取ApplicationContext就是因为spring能够为我们自动地执行了setApplicationContext。但是,spring不会无缘无故地为某个类执行它的方法的,所以,就很有必要通过注册方法类AppUtil的方式告知spring有这样子一个类的存在。其实,方法很简单,就是将方法类AppUtil作为一个普通的bean在spring的配置文件中进行注册:

<bean id="userUtil" class="com.test.core.util.UserUtil"/>

(4)使用静态的成员ApplicationContext类型的对象,appContext,来调用其他bean

AppService localAppService = (AppService)appContext.getBean("appService");

注:配置文件中注入AppService

<bean id="appService" class="com.test.service.AppService">
    ...
</bean>

也可以直接去组件扫描, service类上面加注解:@Service

<!-- 组件扫描 -->
    <context:component-scan
            base-package="com.test.service">
    </context:component-scan>
@Service
public class AppService











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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值