通过工具类SpringContext将所有注册到Spring的Bean工厂(BeanFactory)对象通过注册名或ID返回,并通过registerSingleton实现单例注册,具体参考代码如下
import org.springframework.beans.BeansException;@b@import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;@b@import org.springframework.beans.factory.support.DefaultListableBeanFactory;@b@import org.springframework.context.ApplicationContext;@b@import org.springframework.context.ApplicationContextAware;@b@import org.springframework.web.context.support.XmlWebApplicationContext;@b@@b@public class SpringContext implements ApplicationContextAware {@b@@b@	protected static ApplicationContext context;@b@	protected static ConfigurableListableBeanFactory cbf;@b@	@b@    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {@b@        context = applicationContext;@b@        if(context instanceof XmlWebApplicationContext)@b@        	cbf = ((XmlWebApplicationContext) context).getBeanFactory();@b@    }@b@@b@    public static ApplicationContext getContext() {@b@        return context;@b@    }@b@    @b@    public static ConfigurableListableBeanFactory getBeanFactory() {@b@        return cbf;@b@    }@b@    @b@    @SuppressWarnings("unchecked")@b@	public static <T> T getBean(String beanName){@b@    	return (T) context.getBean(beanName);@b@    }@b@  @b@    public static <T> T getBean(String beanName, Class<T> type){@b@    	return (T) context.getBean(beanName, type);@b@    }@b@    @b@    public static <T> T getBean(Class<T> type){@b@    	return (T) context.getBean(type);@b@    }@b@    @b@    public synchronized static boolean registerSingleton(String beanName, Object bean, boolean isReplace){@b@    	if(cbf == null)return false;@b@    	if(cbf.containsSingleton(beanName) && isReplace) @b@    		destroySingleton(beanName);@b@		cbf.registerSingleton(beanName, bean);@b@    	return true;@b@    }@b@    @b@    //author: yangzelai@b@    public synchronized static void destroySingleton(String beanName){@b@    	if(cbf instanceof DefaultListableBeanFactory){@b@    		DefaultListableBeanFactory factory = (DefaultListableBeanFactory) cbf;@b@    		if(factory.containsSingleton(beanName)){@b@    			factory.destroySingleton(beanName);@b@    		}@b@    	}@b@    }@b@}并将该类配置在spring的xml配置文件
<?xml version="1.0" encoding="UTF-8"?>@b@<beans xmlns="http://www.springframework.org/schema/beans"@b@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"@b@ xsi:schemaLocation="@b@ http://www.springframework.org/schema/beans @b@ http://www.springframework.org/schema/beans/spring-beans.xsd"> @b@ @b@ <bean id="springContext" class="com.woopa.common.persist.SpringContext"/> @b@@b@</beans>