獲取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);
           }

  /**
 * 如果BeanFactory包含一個與所給名稱匹配的bean定義,則返回true
   *
   * @return boolean
  */
  public static boolean containsBean(String name) {
  return applicationContext.containsBean(name);
  }

  /**
  * 判斷以給定名字注冊的bean定義是一個singleton還是一個prototype。
  * 如果與給定名字相應的bean定義沒有被找到,將會拋出一個異常(NoSuchBeanDefinitionException)
  *
  * @return boolean
  */
  public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
  return applicationContext.isSingleton(name);
  }

  /**
  * @return Class 注冊對象的類型
  */
  public static Class<?> getType(String name) throws NoSuchBeanDefinitionException {
  return applicationContext.getType(name);
  }

  /**
  * 如果給定的bean名字在bean定義中有別名,則返回這些別名
  */
  public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {
  return applicationContext.getAliases(name);
  }

  }

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

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

其實

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM