通過持有的Spring應用場景ApplicationContext,可在任何地方獲取bean。
1 import org.apache.commons.logging.Log; 2 import org.apache.commons.logging.LogFactory; 3 import org.springframework.beans.factory.DisposableBean; 4 import org.springframework.context.ApplicationContext; 5 import org.springframework.context.ApplicationContextAware; 6 7 /** 8 * 服務定位器 9 * 持有Spring的應用場景, 可在任何地方獲取bean. 10 */ 11 public final class ServiceLocator implements ApplicationContextAware, DisposableBean { 12 13 private static Log logger = LogFactory.getLog(ServiceLocator.class); 14 private static ApplicationContext context = null; 15 16 /** 17 * 實現ApplicationContextAware接口, 注入Context到靜態變量中. 18 * @param context 19 */ 20 @Override 21 public void setApplicationContext(ApplicationContext context) { 22 logger.debug("Injected the ApplicationContext into ServiceLocator:" + context); 23 if (ServiceLocator.context != null) { 24 logger.debug("[------------ ApplicationContext in the ServiceLocator " + 25 "is covered, as the original ApplicationContext is:" 26 + ServiceLocator.context + " ------------]"); 27 } 28 ServiceLocator.context = context; 29 } 30 31 /** 32 * 實現DisposableBean接口,在Context關閉時清理靜態變量. 33 */ 34 @Override 35 public void destroy() throws Exception { 36 ServiceLocator.clear(); 37 } 38 39 /** 40 * 取得存儲在靜態變量中的ApplicationContext. 41 * @return 42 */ 43 public static ApplicationContext getApplicationContext() { 44 assertContextInjected(); 45 return context; 46 } 47 48 /** 49 * 從Spring的應用場景中取得Bean, 自動轉型為所賦值對象的類型. 50 * @param name bean名稱 51 * @return bean對象 52 */ 53 @SuppressWarnings("unchecked") 54 public static <T> T getService(String name) { 55 assertContextInjected(); 56 return (T) context.getBean(name); 57 } 58 59 /** 60 * 從Spring的應用場景中取得Bean, 自動轉型為所賦值對象的類型. 61 * @param requiredType bean類 62 * @return bean對象 63 */ 64 public static <T> T getService(Class<T> requiredType) { 65 assertContextInjected(); 66 return context.getBean(requiredType); 67 } 68 69 /** 70 * 清除ServiceLocator中的ApplicationContext 71 */ 72 public static void clear() { 73 logger.debug("Clear ApplicationContext in ServiceLocator :" + context); 74 context = null; 75 } 76 77 /** 78 * 檢查ApplicationContext不為空. 79 */ 80 private static void assertContextInjected() { 81 if (context == null) { 82 throw new IllegalStateException("ApplicaitonContext not injected, " + 83 "as defined in the context.xml ServiceLocator"); 84 } 85 } 86 } View Code
調用getService函數,分為按名稱和類型獲取。
1 /** 2 * 從Spring的應用場景中取得Bean, 自動轉型為所賦值對象的類型. 3 * @param name bean名稱 4 * @return bean對象 5 */ 6 @SuppressWarnings("unchecked") 7 public static <T> T getService(String name) { 8 assertContextInjected(); 9 return (T) context.getBean(name); 10 } 11 12 /** 13 * 從Spring的應用場景中取得Bean, 自動轉型為所賦值對象的類型. 14 * @param requiredType bean類 15 * @return bean對象 16 */ 17 public static <T> T getService(Class<T> requiredType) { 18 assertContextInjected(); 19 return context.getBean(requiredType); 20 }