ClassLoader 與 配置文件

                    ClassLoader 與 配置文件

   現在,無論是企業應用還是小型項目,爲了產品的靈活性、擴展性,
   配置文件越來越多,以我自己嘗試的一個web應用來說,在xml配置文件中,
   添加自己的配置參數或初始化參數時遇到的關於“參數的路徑與處理這個參數的類的classloader有關”,
   比如,在我前面做的(小框架中),
   <bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
      <property name="location">
        <value>/WEB-INF/classes/properties/init.properties</value>
      </property>
   </bean>
   配置了Spring初始化需要的參數,有的開源項目處理時是自己寫的類處理的,或者利用Spring處理,
   (spring的類是/WEB-INF/classes/org/springframework/....)
   所以參數如果需要路徑一般寫爲"/properties/*.* ",而如果你利用容器的一些東西處理,
   比如說apache中的類處理,那麼你就要將參數改寫爲"/WEB-INF/classes/properties/*.* ",(比如我們的包結構爲com.myapp),
   那麼我們用自己的類處理時,加載我們類的classloader是com.myapp....(指WEB-INF/classes/ 下),
   如果是apache的類處理時,加載類的classloader就是加載web應用上面的(比如我的應用D:/myapp/WEB-INF/......),這樣
   classloader加載參數時從myapp開始,所以參數必須加上/WEB-INF/classes/.....纔可以。
  
   Resource--getInputStream()方法,
   你就會發現他的classloader是什麼了!!!
   public InputStream getInputStream() throws IOException {
  InputStream is = null;
  if (this.clazz != null) {
   is = this.clazz.getResourceAsStream(this.path);
  }
  else {
   ClassLoader cl = this.classLoader;
   if (cl == null) {
    // no class loader specified -> use thread context class loader
    cl = Thread.currentThread().getContextClassLoader();
   }
   is = cl.getResourceAsStream(this.path);
  }
  if (is == null) {
   throw new FileNotFoundException(
     getDescription() + " cannot be opened because it does not exist");
  }
  return is;
    }

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章