1. 程式人生 > >獲取Spring的上下文環境ApplicationContext的方式

獲取Spring的上下文環境ApplicationContext的方式

Web專案中發現有人如此獲得Spring的上下環境:

public class SpringUtil {

   public static ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

   public static Object getBean(String serviceName){
         return context.getBean(serviceName);
   }

}

在web專案中這種方式非常不可取!!!

分析:

首先,主要意圖就是獲得Spring上下文;

其次,有了Spring上下文,希望通過getBean()方法獲得Spring管理的Bean的物件;

最後,為了方便呼叫,把上下文定義為static變數或者getBean方法定義為static方法;

但是,在web專案中,系統一旦啟動,web伺服器會初始化Spring的上下文的,我們可以很優雅的獲得Spring的ApplicationContext物件。

如果使用

new ClassPathXmlApplicationContext(“applicationContext.xml”);
相當於重新初始化一遍!!!!

也就是說,重複做啟動時候的初始化工作,第一次執行該類的時候會非常耗時!!!!!

正確的做法是:

@Component
public class SpringContextUtil implements ApplicationContextAware {

     private static ApplicationContext applicationContext; // Spring應用上下文環境

     /*

      * 實現了ApplicationContextAware 介面,必須實現該方法;

      *通過傳遞applicationContext引數初始化成員變數applicationContext

      */

     public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
           SpringContextUtil.applicationContext = applicationContext;
     }



     public static ApplicationContext getApplicationContext() {
            return applicationContext;
     }


      @SuppressWarnings("unchecked")
      public static <T> T getBean(String name) throws BeansException {
                 return (T) applicationContext.getBean(name);
       }

}

注意:這個地方使用了Spring的註解@Component,如果不是使用annotation的方式,而是使用xml的方式管理Bean,記得寫入配置檔案

其實
ApplicationContext context = new ClassPathXmlApplicationContext(“applicationContext.xml”);
這種方式獲取Sping上下文環境,最主要是在測試環境中使用,比如寫一個測試類,系統不啟動的情況下手動初始化Spring上下文再獲取物件!