很多時候,我們在普通的java類中需要獲取spring的bean來做操作,比如,在線程中,我們需要操作數據庫,直接通過spring的bean中構建的service就可以完成。無需自己寫鏈接。。有時候有些好的東西,拿到用就好了。
這里是多種方式中的一種。
通過實現ApplicationContextAware獲取bean。這里有個問題,就是,如果spring容器沒有啟動完成的時候,不能通過這個方法獲取,因為這樣,會報空指針,因為
private static ApplicationContext applicationContext;
這個還沒有加載完成。好的開始貼代碼。。
java類:
1 package com.iafclub.demo.util; 2 3 import java.util.Map; 4 5 import org.springframework.context.ApplicationContext; 6 import org.springframework.context.ApplicationContextAware; 7 8 /**獲取javabean工具類 9 * 10 * @author chenweixian 11 * 12 */ 13 public class ApplicationUtil implements ApplicationContextAware{ 14 15 private static ApplicationContext applicationContext; 16 17 //實現ApplicationContextAware接口的context注入函數, 將其存入靜態變量. 18 public void setApplicationContext(ApplicationContext applicationContext) { 19 ApplicationUtil.applicationContext = applicationContext; 20 } 21 22 23 //取得存儲在靜態變量中的ApplicationContext. 24 public static ApplicationContext getApplicationContext() { 25 checkApplicationContext(); 26 return applicationContext; 27 } 28 29 //從靜態變量ApplicationContext中取得Bean, 自動轉型為所賦值對象的類型. 30 @SuppressWarnings("unchecked") 31 public static <T> T getBean(String name) { 32 checkApplicationContext(); 33 if (applicationContext == null){ 34 return null; 35 } 36 return (T) applicationContext.getBean(name); 37 } 38 39 40 //從靜態變量ApplicationContext中取得Bean, 自動轉型為所賦值對象的類型. 41 //如果有多個Bean符合Class, 取出第一個. 42 @SuppressWarnings("unchecked") 43 public static <T> T getBean(Class<T> clazz) { 44 checkApplicationContext(); 45 @SuppressWarnings("rawtypes") 46 Map beanMaps = applicationContext.getBeansOfType(clazz); 47 if (beanMaps!=null && !beanMaps.isEmpty()) { 48 return (T) beanMaps.values().iterator().next(); 49 } else{ 50 return null; 51 } 52 } 53 54 private static void checkApplicationContext() { 55 if (applicationContext == null) { 56 // throw new IllegalStateException("applicaitonContext未注入,請在applicationContext.xml中定義SpringContextHolder"); 57 } 58 } 59 60 }
配置文件:
1 <bean id="applicationUtil" class="com.iafclub.demo.util.ApplicationUtil" />
啟動完成。
測試:OK
1 (RedisTemplate<String, Serializable>) ApplicationUtil.getBean("redisTemplate");