通过SpringContextUtil获取spring环境上下文

本文介绍如何创建Spring工具类SpringContextUtil以方便获取Spring配置文件中的bean实例,并通过实例演示了如何在代码中利用该工具类获取缓存服务bean。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.写个工具类SpringContextUtil,实现ApplicationContextAware接口,并完成ApplicationContext初始化。可以调用getBean(String name)方法通过已初始化的ApplicationContext获取spring配置文件中已注册的bean实例。

<pre name="code" class="java">public class SpringContextUtil implements ApplicationContextAware{
	private static ApplicationContext applicationContext;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext){
		SpringContextUtil.applicationContext = applicationContext;
	}

	public static ApplicationContext getApplicationContext(){
		return applicationContext;
	}

	public static Object getBean(String name) throws BeansException{
		return applicationContext.getBean(name);
	}
}




2.在spring配置文件applicationContext.xml中配置如下:

<bean id="SpringContextUtil" class="com.odchina.micro.util.SpringContextUtil" lazy-init="false"></bean>
<pre name="code" class="html"><bean id="memCacheService" class="com.odchina.micro.common.cache.XMemcachedimpl">
	<property name="memcachedClient" ref="memcachedClient" />
	<property name="memcachedClientEnhance" ref="memcachedClientEnhance" />
	<property name="expireTime" value="108000000" /><!-- 数据过期时间,单位毫秒 -->
	<property name="is_updataExp" value="true" />
</bean>
<bean id="memcachedClientEnhance" class="com.odchina.micro.common.cache.MemCachedClientEnhance">
	<property name="memcachedClient" ref="memcachedClient" />
</bean>	
<bean id="memcachedClient" class="com.danga.MemCached.MemCachedClient" />



3.代码中使用SpringContextUtil获取已注册bean实例

private CacheService memCacheService=(CacheService) SpringContextUtil.getBean("memCacheService");

本文是我结合网上所查资料和自己的项目总结出来的,如有错误,恳请指正。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值