1. 程式人生 > >自定義SpringContextHolder獲取bean例項(一)

自定義SpringContextHolder獲取bean例項(一)

載入Spring配置檔案時,如果Spring配置檔案中所定義的Bean類實現了ApplicationContextAware 介面,那麼在載入Spring配置檔案時,會自動呼叫ApplicationContextAware 介面中的

public void setApplicationContext(ApplicationContext context) throws BeansException

方法,獲得ApplicationContext物件。

前提必須在Spring配置檔案中指定該類。

    public class SpringContextHolder implements ApplicationContextAware {  
      
         /** 
          * 以靜態變數儲存ApplicationContext,可在任意程式碼中取出ApplicaitonContext. 
          */  
        private static ApplicationContext context;  
      
        /** 
         * 實現ApplicationContextAware介面的context注入函式, 將其存入靜態變數. 
         */  
        public void setApplicationContext(ApplicationContext context) {  
            SpringContextHolder.context =context;  
        }     
        public static ApplicationContext getApplicationContext() {  
            return context;  
        }  
        /** 
         * 從靜態變數ApplicationContext中取得Bean, 自動轉型為所賦值物件的型別. 
         */  
        public static <T> T getBean(String name) {  
            return (T) context.getBean(name);  
        }  
    }  
bean中:

Java程式碼  收藏程式碼

<bean id="springContextHolder" class="com.enation.framework.context.spring.SpringContextHolder" />

呼叫:

Java程式碼  收藏程式碼
ICartManager cartManager = SpringContextHolder.getBean("cartManager"); 

正常情況:

Java程式碼  收藏程式碼
    public class AppManager extends ContextLoaderListener implements  ServletContextListener {  
      
        private ServletContext context;  
        private WebApplicationContext webApplicationContext;  
      
        public void contextInitialized(ServletContextEvent sce) {  
            this.context = sce.getServletContext();  
            this.webApplicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(context);  
            this.context.setAttribute("WEBAPPLICATIONCONTEXT", webApplicationContext);  
      
        }  

Java程式碼  收藏程式碼
HttpSession session = request.getSession();  
WebApplicationContext webApplicationContext = (WebApplicationContext)session.getServletContext().getAttribute("WEBAPPLICATIONCONTEXT");  
UnsubscribeEmailFacade unsubscribeEmailFacade = (UnsubscribeEmailFacade)webApplicationContext.getBean("unsubscribeEmailFacade"); 
法2: org.springframework.web.context.ContextLoader
// 獲取spring bean容器  
    WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();  
    ISysConfigDao sysconfigdao = (ISysConfigDao) wac.getBean("iSysConfigDao");