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

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

Web項目中發現有人如此得到Spring的上下環境:web

 

public class SpringUtil {spring

       public static ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
 
       public static Object getBean(String serviceName){
             return context.getBean(serviceName);
       }
}
服務器

 

 

在web項目中這種方式很是不可取!!!app

分析:測試

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

其次,有了Spring上下文,但願經過getBean()方法得到Spring管理的Bean的對象;xml

最後,爲了方便調用,把上下文定義爲static變量或者getBean方法定義爲static方法;對象

 

可是,在web項目中,系統一旦啓動,web服務器會初始化Spring的上下文的,咱們能夠很優雅的得到Spring的ApplicationContext對象。接口

若是使用get

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,記得寫入配置文件

<bean id="springContextUtil" class="com.ecdatainfo.util.SpringContextUtil" singleton="true" />

 

其實

ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
這種方式獲取Sping上下文環境,最主要是在測試環境中使用,好比寫一個測試類,系統不啓動的狀況下手動初始化Spring上下文再獲取對象!

相關文章
相關標籤/搜索