普通java bean中获取Spring的ApplicationContext

很多情况下,我们需要在普通javabean中获取spring 配置文件中的bean。

1.创建一个类 ,让其实现org.springframework.context.ApplicationContextAware接口来让Spring在启动的时候为我们注入ApplicationContext对象.
不实现ApplicationContextAware接口应该也是可以的,不过我这里测试没通过。

示例代码:
public class MyApplicationContextUtil implements ApplicationContextAware{
private static ApplicationContext context;//声明一个静态变量保存
public void setApplicationContext(ApplicationContext contex)
throws BeansException {
this.context=contex;
}
public static ApplicationContext getContext(){
return context;
}
}


2.在applicationContext.xml文件中配置此bean,以便让Spring启动时自动为我们注入ApplicationContext对象.
<!-- 这个bean主要是为了得到ApplicationContext 所以它不需要其它属性-->
<bean id="myApplicationContextUtils" class="org.ing.springutil.MyApplicationContextUtil"></bean>

3.有了这个bean取得ApplicationContext之后我们就可以调用其getBean("beanName")方法来得到由Spring 管理所有对象.

ApplicationContext springContext = MyApplicationContextUtils.getApplicationContext();
ITesTaskExcuteService tesTaskExcuteService=(ITesTaskExcuteService)springContext.getBean("tesTaskExcuteService");
这样就可以取得你想要的spring bean。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值