Spring中ApplicationContextAware的用法

本文介绍Spring框架中ApplicationContextAware接口的作用及使用方法。通过实现该接口,类能直接获取Spring配置文件中的所有bean对象。文章详细展示了如何通过示例类AppUtil实现接口并获取指定bean的过程。

一、这个接口有什么用?

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


二、怎么用?

举个例子吧:

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

1、因为spring要建立属于自己的容器,就必须要加载自己的配置文件。

     这个时候,需要注册ContextLoaderListener或者这个类的子类。

在web.xml加上以下的信息:

1
<p style="line-height: normal;"><listener><br>        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class><br> </listener><br></p>

当然,这样子的话只会读取默认路径下的application.xml配置文件的。如果需要读取特定路径下的配置文件。需要在web.xml中


添加如下信息。可以参考我的示例,指定配置文件,如下:


1
<p style="line-height: normal;"><context-param><br>        <param-name>contextConfigLocation</param-name><br>        <param-value>classpath:conf/app-context.xml</param-value><br> </context-param><br></p>


注意:

1
<p style="line-height: normal;"><param-name>contextConfigLocation</param-name><br></p>

是不能改变的。


2、方法类AppUtil的处理


方法类AppUtil实现ApplicationContextAware接口:

1
<p style="line-height: normal;">public class AppUtil<br>  implements ApplicationContextAware<br></p>

为方法类AppUtil增加一个静态的成员ApplicationContext类型的对象。以后方法类AppUtil获取ApplicationContext,就是通过读取这个


成员变量的。具体如下所示:

1
<p style="line-height: normal;">private static ApplicationContext appContext;<br></p>

 实现ApplicationContextAware接口的默认方法:

1
<p style="line-height: normal;"public void setApplicationContext(ApplicationContext paramApplicationContext)<br>    throws BeansException<br>  {<br>    appContext = paramApplicationContext;<br>  }<br></p>

 

3、在spring的配置文件中,注册方法类AppUtil


严格上来说,方法类AppUtil是一个bean,而且从步骤2中我们不难发现,之所以方法类AppUtil能够灵活自如地获取ApplicationContext

就是因为spring能够为我们自动地执行了setApplicationContext。但是,spring不会无缘无故地为某个类执行它的方法的,所以,就很有必要通过注册方法类AppUtil的方式告知spring有这样子一个类的存在。


其实,方法很简单,就是将方法类AppUtil作为一个普通的bean在spring的配置文件中进行注册:

1
<p style="line-height: normal;"><bean id="appUtil" class="com.htsoft.core.util.AppUtil"/><br></p>

4、使用静态的成员ApplicationContext类型的对象,appContext,来调用其他bean。在方法类AppUtil中增加如下方法:


1
<p style="line-height: normal;">public static Object getBean(String paramString)<br>  {<br>    return appContext.getBean(paramString);<br>  }<br></p>

那么,在方法类AppUtil中就能够灵活地调用其他任何一个bean了,例如:

1
<p style="line-height: normal;">CompanyService localCompanyService = (CompanyService)getBean("companyService");<br></p>

注:配置文件中关于companyService的内容:


1
<p style="line-height: normal;"><bean id="companyService" class="com.kaiwii.service.system.impl.CompanyServiceImpl"><br>        <constructor-arg index="0" ref="companyDao"/>      <br></bean><br></p>


特别说明:尊重作者的劳动成果,转载请注明出处哦~~~
http://blog.yemou.net/article/query/info/tytfjhfascvhzxcyt379
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值