SpringBeanUtil工具類


 1 package com.missy.util;
 2 
 3 import org.springframework.beans.BeansException;
 4 import org.springframework.context.ApplicationContext;
 5 import org.springframework.context.ApplicationContextAware;
 6 import org.springframework.stereotype.Component;
 7  
 8 @Component
 9 public class SpringBeanUtil implements ApplicationContextAware {
10     private static ApplicationContext applicationContext = null;
11     @Override
12     public void setApplicationContext(ApplicationContext applicationContext) throws             
13                 BeansException {
14         SpringBeanUtil.applicationContext = applicationContext;
15     }
16     
17     /**
18      * 從靜態變量applicationContext中得到Bean, 自動轉型為所賦值對象的類型.
19      */
20     @SuppressWarnings("unchecked")
21     public static <T> T getBean(String name) {
22         if(name == null || applicationContext == null)
23             return null;
24         return (T) applicationContext.getBean(name);
25     }
26  
27     /**
28      * 從靜態變量applicationContext中得到Bean, 自動轉型為所賦值對象的類型.
29      */
30     public static <T> T getBean(Class<T> clazz) {
31         return applicationContext.getBean(clazz);
32     }
33  
34 }

 調用:

XService  x = SpringBeanUtil.getBean(XService.class);

 


 

微信公眾號:敲代碼的小浪漫

歡迎大家關注~


免責聲明!

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



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