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 }    

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM