SpringContextHolder 獲取bean
阿新 • • 發佈:2019-02-15
使用註解形式進行載入,實現ApplicationContextAware介面並複寫setApplicationContext方法。
將上下文環境物件以靜態變數儲存下來。則可以在工具類中使用SpringContextHolder.getBean()的方法獲取實體或者service進行操作資料
使用@Service註解形式進行實體注入
package com.hema.common.utils; import java.net.HttpURLConnection; import java.net.URL; import java.util.Date; import org.apache.commons.lang3.Validate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.DisposableBean; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; /** * 以靜態變數儲存Spring ApplicationContext, 可在任何程式碼任何地方任何時候取出 * ApplicaitonContext. * * @date 2013-5-29 下午1:25:40 */ @Service @Lazy(false) public class SpringContextHolder implements ApplicationContextAware, DisposableBean { private static ApplicationContext applicationContext = null; private static Logger logger = LoggerFactory.getLogger(SpringContextHolder.class); /** * 取得儲存在靜態變數中的ApplicationContext. */ public static ApplicationContext getApplicationContext() { assertContextInjected(); return applicationContext; } /** * 從靜態變數applicationContext中取得Bean, 自動轉型為所賦值物件的型別. */ @SuppressWarnings("unchecked") public static <T> T getBean(String name) { assertContextInjected(); return (T) applicationContext.getBean(name); } /** * 從靜態變數applicationContext中取得Bean, 自動轉型為所賦值物件的型別. */ public static <T> T getBean(Class<T> requiredType) { assertContextInjected(); return applicationContext.getBean(requiredType); } /** * 清除SpringContextHolder中的ApplicationContext為Null. */ public static void clearHolder() { if (logger.isDebugEnabled()){ logger.debug("清除SpringContextHolder中的ApplicationContext:" + applicationContext); } applicationContext = null; } /** * 實現ApplicationContextAware介面, 注入Context到靜態變數中. */ @Override public void setApplicationContext(ApplicationContext applicationContext) { SpringContextHolder.applicationContext = applicationContext; } /** * 實現DisposableBean介面, 在Context關閉時清理靜態變數. */ @Override public void destroy() throws Exception { SpringContextHolder.clearHolder(); } /** * 檢查ApplicationContext不為空. */ private static void assertContextInjected() { Validate.validState(applicationContext != null, "applicaitonContext屬性未注入, 請在applicationContext.xml中定義SpringContextHolder."); } }