java web路徑和spring讀取配置檔案
阿新 • • 發佈:2019-01-24
此篇部落格緣起:部署java web系統到阿里雲伺服器(ubuntu14.04)的時候,有以下兩個問題
- 找不到自定義的property配置檔案
- 上傳圖片的時候找不到路徑
開發的時候是在windows上的,執行正常,部署的時候就出問題了,肯定是windows和linux路徑區別導致的(一個小問題來回鼓搗了幾個小時,因為有自己對windows下和linux下的區別還不是特別瞭解,還有就是每次在windows下修改完成以後都要重新上傳到阿里雲,專案較大來回也需要較多時間。。。),遂決定好好看看java web路徑的問題。
普通java程式獲取路徑
Thread.currentThread().getContextClassLoader().getResource("/").toURI().getPath()null Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath() /D:/workspace/EPEducationManager/build/classes/ UserResource.class.getClassLoader().getResource("/").toURI().getPath() null UserResource.class.getClassLoader().getResource("").toURI().getPath() /D:/workspace/EPEducationManager/build/classes/ UserResource.class.getResource("").toURI().getPath() /D:/workspace/EPEducationManager/build/classes/com/phy/em/user/rest/ UserResource.class.getResource("/").toURI().getPath() /D:/workspace/EPEducationManager/build/classes/ System.getProperty("user.dir") D:\workspace\EPEducationManager
在java web中獲取路徑
Thread.currentThread().getContextClassLoader().getResource("/").toURI().getPath()/D:/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/EPEducationManager/WEB-INF/classes/ Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath() /C:/tomcat7/lib/ UserResource.class.getClassLoader().getResource("/").toURI().getPath() /D:/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/EPEducationManager/WEB-INF/classes/ UserResource.class.getClassLoader().getResource("").toURI().getPath() /C:/tomcat7/lib/ UserResource.class.getResource("").toURI().getPath() /D:/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/EPEducationManager/WEB-INF/classes/com/phy/em/user/rest/ UserResource.class.getResource("/").toURI().getPath() /C:/tomcat7/lib/ System.getProperty("user.dir") C:\Program Files (x86)\eclipse
根據上面的輸出選擇對應的獲取路徑的方法,特別注意獲取得到的path前面有"/",不要手賤刪除"/",對,我就是那個手賤的人,刪除了"/",因為看到前面有斜槓在windows資源管理器中是打不開的,我就刪除了,結果在windows上執行是正確的,但是部署在linux上的時候把"/"刪除了就成了"var/share/lib",明顯這個錄警示不正確的,本來是根目錄下var...成了當前目錄下var...
獲取路徑就可以讀取制定目錄下的配置檔案了
使用spring讀取配置檔案
在xml中讀取
<bean id=”propertyConfigurer” class=”org.springframework.beans.factory.config.PropertyPlaceholderConfigurer”> <property name=”location”> <value>/WEB-INF/configInfo.properties</value> </property> <property name=”fileEncoding” value=”utf-8″ /> </bean>
在xml中使用
<property name=”host”> <value>${email.host}</value> </property> <property name=”port”> <value>${email.port}</value> </property>
通過以上兩步就可以完成在讀取property配置檔案並注入到對應的bean中,但是有時候我們並不需要為了讀取配置而建立一個bean,我們只想程式碼中直接讀取配置檔案,可以使用如下的方式
ResourceUtils.getFile("classpath:config.properties").getPath()
D:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\EPEducationManager\WEB-INF\classes\
可以直接在程式碼中使用"classpath"來定位配置檔案,獲取得到的是一個File物件,當然了獲取路徑肯定沒問題