springmvc手動獲取bean

@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."); } }
相關文章
相關標籤/搜索