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