javascript
Spring.Resource与Spring资源获取方式
講到資源,就得提下Spring獲取資源方式,常用的有兩種 通過Resource接口的子類獲取資源通過ResourceLoader接口的子類獲取資源
Spring.Resource 資源操作函數(shù)一覽
//判斷資源是否存在
boolean exists(); //
//返回當(dāng)前資源對(duì)應(yīng)的URL,不能解析則會(huì)拋出異常;如ByteArrayResource就不能解析為一個(gè)URL
URL getURL() throws IOException;
//返回當(dāng)前資源對(duì)應(yīng)的URI
URI getURI() throws IOException;
//返回當(dāng)前資源對(duì)應(yīng)的File
File getFile() throws IOException;
//返回對(duì)應(yīng)的ReadableByteChannel
default ReadableByteChannel readableChannel() throws IOException
介紹下Resource相關(guān)子類的使用
1 FileSystemResource:通過文件系統(tǒng)獲取資源
Resource resource = new FileSystemResource(“D:/example.txt”);
File file= new File(“example.txt”);
Resource resource2 = new FileSystemResource(file);
2 ByteArrayResource:獲取byte數(shù)組表示的資源 基于ByteArrayInputStream和字節(jié)數(shù)組實(shí)現(xiàn),應(yīng)用場(chǎng)景類似ByteArrayInputStream,緩存byte[]資源
3 ClassPathResource:獲取類路徑下的資源
//ClassPathResource.java 的三個(gè)屬性
private final String path;
//使用Class或ClassLoader加載資源
private ClassLoader classLoader;
private Class<?> clazz;
—使用方式----
Resource resource = new ClassPathResource(“test.txt”);
4 InputStreamResource:接收一個(gè)InputStream對(duì)象,獲取輸入流封裝的資源
5 ServletContextResourse:加載ServletContext環(huán)境下(相對(duì)于Web應(yīng)用根目錄的)路徑資源,獲取的資源
6 UrlResource:通過URL訪問http資源和FTP資源等
總結(jié)
以上是生活随笔為你收集整理的Spring.Resource与Spring资源获取方式的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: URL概念及与URL的区别
- 下一篇: gradle idea java ssm