1.写一个SpringContext的工具类 实现ApplicationContextAware接口
1 import org.springframework.beans.BeansException; 2 import org.springframework.beans.factory.NoSuchBeanDefinitionException; 3 import org.springframework.context.ApplicationContext; 4 import org.springframework.context.ApplicationContextAware; 5 6 public class SpringContextUtil implements ApplicationContextAware{ 7 8 private static ApplicationContext applicationContext; //Spring应用上下文环境 9 10 public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { 11 SpringContextUtil.applicationContext = applicationContext; 12 } 13 14 public static ApplicationContext getApplicationContext() { 15 return applicationContext; 16 } 17 18 public static Object getBean(String name) throws BeansException { 19 return applicationContext.getBean(name); 20 } 21 22 public static Object getBean(String name, Class requiredType) throws BeansException { 23 return applicationContext.getBean(name, requiredType); 24 } 25 26 public static boolean containsBean(String name) { 27 return applicationContext.containsBean(name); 28 } 29 30 public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException { 31 return applicationContext.isSingleton(name); 32 } 33 34 public static Class getType(String name) throws NoSuchBeanDefinitionException { 35 return applicationContext.getType(name); 36 } 37 38 public static String[] getAliases(String name) throws NoSuchBeanDefinitionException { 39 return applicationContext.getAliases(name); 40 } 41 42 }
2,Spring配置文件中添加关于该工具类的bean配置
<bean id="SpringContextUtil " class="util.SpringContextUtil " />
3.代码中使用
MongoTemplate temp = (MongoTemplate)SpringContextUtil.getBean("mongoTemplate");