1. 程式人生 > >Spring Boot參考教程(七)Spring Boot Jar方式讀取資源文件

Spring Boot參考教程(七)Spring Boot Jar方式讀取資源文件

font 類加載器 獲取文件路徑 使用 解壓 源文件 fonts align 類加載

5. Spring Boot Jar方式讀取資源文件

2.2.2章節中已說明SpringBoot的一個特性就是獨立運行,內嵌Servlet容器。

Spring Boot工程以jar方式獨立運行開發時會遇到一些問題,本章節主要說明讀取靜態資源文件的問題。

註:SpringBoot打包為jar啟動時不會將jar解壓,所以不能以獲取文件路徑的方式讀取資源文件,而是要直接獲取文件流,且讀取文件流時使用的類加載器要用ClassUtils.class.getClassLoader()的加載器,具體和SpringBoot以jar方式啟動的加載器用途有關,感興趣自己研究。

編寫代碼如下:

技術分享

技術分享

將工程打成jar

技術分享

jar啟動

技術分享

訪問測試:

技術分享

<實例代碼>

Github:https://github.com/chunyuding/SpringBoot-Demo

https://github.com/chunyuding/SpringBoot-Demo.git

碼雲:https://gitee.com/dingchunyu/SpringBoot-Demo

https://gitee.com/dingchunyu/SpringBoot-Demo.git

<推薦書籍>

百度雲:http://pan.baidu.com/s/1qYA0Nxi

Spring Boot參考教程(七)Spring Boot Jar方式讀取資源文件