- 名師講壇:Spring實戰開發(Redis+SpringDataJPA+SpringMVC+SpringSecurity)
- 李興華
- 405字
- 2020-04-24 14:20:47
4.2 讀取不同資源
Resource表示所有資源的統一訪問標準。在Resource接口中有4個常用接口子類:ByteArrayResource(內存資源)、ClassPathResource(CLASSPATH下定位資源)、FileSystemResource(文件資源)和UrlResource(網絡資源),如圖4-1所示。

圖4-1 Resource接口常用子類
1.【mldnspring-base模塊】編寫程序,實現內存資源讀取。

本程序實現了一個內存資源的讀取操作,在進行內存資源讀取時需要通過ByteArrayResource類的構造方法設置要讀取的資源內容,而后就可以采用Resource接口中的getInputStream方法獲取數據輸入流對象。
2.【mldnspring-base模塊】進行文件資源讀取,使用FileSystemResource子類完成。

本程序利用FileSystemResource子類實現了本地文件的讀取,在構造FileSystemResource類對象時傳遞了要讀取的資源路徑,而后依然利用Resource接口標準實現數據讀取。
3.【mldnspring-base模塊】讀取CLASSPATH資源。

本程序讀取了在源文件夾目錄之中的Spring配置文件信息,直接使用ClassPathResource類簡化了CLASSPATH路徑的訪問。
4.【mldnspring-base模塊】讀取網絡資源,路徑為http://localhost/mldn/mldn-data.txt。

通過以上4個資源讀取程序,相信讀者已經發現了,Spring之所以需要設置Resource接口標準,是為了對資源訪問進行統一管理,即通過Resource接口子類彌補InputStream類的功能局限。
推薦閱讀
- 精通Nginx(第2版)
- Java面向對象思想與程序設計
- Silverlight魔幻銀燈
- Visual C++數字圖像處理技術詳解
- Microsoft System Center Orchestrator 2012 R2 Essentials
- Android 應用案例開發大全(第3版)
- Spring+Spring MVC+MyBatis整合開發實戰
- Mastering Xamarin.Forms(Second Edition)
- HTML5 APP開發從入門到精通(微課精編版)
- CRYENGINE Game Development Blueprints
- Xamarin Blueprints
- CodeIgniter Web Application Blueprints
- Angular Design Patterns
- Appcelerator Titanium:Patterns and Best Practices
- 軟件測試分析與實踐