1. 程式人生 > >springboot獲取專案跟目錄

springboot獲取專案跟目錄

springboot部署之後無法獲取專案目錄的問題:

之前看到網上有提問在開發一個springboot的專案時,在專案部署的時候遇到一個問題:就是我將專案匯出為jar包,然後用java -jar 執行時,專案中檔案上傳的功能無法正常執行,其中獲取到存放檔案的目錄的絕對路徑的值為空,檔案無法上傳。問題連結

不清楚此網友具體是怎麼實現的,通常我們可以通過如下方案解決:

//獲取跟目錄
File path = new File(ResourceUtils.getURL("classpath:").getPath());
if(!path.exists()) path = new File(""
); System.out.println("path:"+path.getAbsolutePath()); //如果上傳目錄為/static/images/upload/,則可以如下獲取: File upload = new File(path.getAbsolutePath(),"static/images/upload/"); if(!upload.exists()) upload.mkdirs(); System.out.println("upload url:"+upload.getAbsolutePath()); //在開發測試模式時,得到的地址為:{專案跟目錄}/target/static/images/upload/
//在打包成jar正式釋出時,得到的地址為:{釋出jar包目錄}/static/images/upload/

另外使用以上程式碼需要注意,因為以jar包釋出時,我們儲存的路徑是與jar包同級的static目錄,因此我們需要在jar包目錄的application.properties配置檔案中設定靜態資源路徑,如下所示:

#設定靜態資源路徑,多個以逗號分隔
spring.resources.static-locations=classpath:static/,file:static/

以jar包釋出springboot專案時,預設會先使用jar包跟目錄下的application.properties來作為專案配置檔案。