Spring Boot中普通类获取Spring容器中的Bean

我们知道如果我们要在一个类使用spring提供的bean对象,我们需要把这个类注入到spring容器中,交给spring容器进行管理,但是在实际当中,我们往往会碰到在一个普通的Java类中,自己动手new的对象,想直接使用spring提供的其他对象或者说有一些不需要交给spring管理,但是需要用到spring里的一些对象;

虽然通过

ApplicationContext ac = new FileSystemXmlApplicationContext("applicationContext.xml");

ac.getBean("beanId") 

 

方式加载xml文件来获取上下文环境获得bean,但由于在web application中,spring是通过web.xml加载配置的,所有会加载两次spring容器,同时在spring boot中一般是无xml配置的,所以需要其他方式了;

1.通过实现 ApplicationContextAware接口 定义一个SpringUtil工具类,实现ApplicationContextAware接口

 1 public class SpringUtil implements ApplicationContextAware { 
 2 private static ApplicationContext applicationContext; 
 3 
 4     @Override 
 5     public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
 6         if(SpringUtil.applicationContext == null) { 
 7             SpringUtil.applicationContext = applicationContext; 
 8         } 
 9     } 
10 
11     //获取applicationContext 
12     public static ApplicationContext getApplicationContext() { 
13         return applicationContext; 
14     } 
15 
16     //通过name获取 Bean. 
17     public static Object getBean(String name){ 
18         return getApplicationContext().getBean(name); 
19     } 
20 
21     //通过class获取Bean. 
22     public static T getBean(Class clazz){ 
23         return getApplicationContext().getBean(clazz); 
24     } 
25 
26     //通过name,以及Clazz返回指定的Bean 
27     public static T getBean(String name,Class clazz){ 
28         return getApplicationContext().getBean(name, clazz); 
29     } 
30 }    

 

posted @ 2017-11-15 00:11  icebearrr  阅读(2416)  评论(0编辑  收藏  举报