通过SpringContextUtil获取spring环境上下文

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");

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




你可能感兴趣的:(spring获取bean,spring环境上下文)