码迷,mamicode.com
首页 > 编程语言 > 详细

Spring通过配置文件获取bean(不用IOC)

时间:2015-06-11 09:23:25      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:

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 }
View Code

2,Spring配置文件中添加关于该工具类的bean配置

 <bean id="SpringContextUtil " class="util.SpringContextUtil "  />

3.代码中使用

MongoTemplate temp = (MongoTemplate)SpringContextUtil.getBean("mongoTemplate");

 

Spring通过配置文件获取bean(不用IOC)

标签:

原文地址:http://www.cnblogs.com/dobestself-994395/p/4568011.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!