文章內(nèi)容來自本人學(xué)習(xí)《精通Spring 4.x 企業(yè)應(yīng)用開發(fā)實戰(zhàn)》一書的筆記整理,部分內(nèi)容摘抄原文。
為了訪問不同類型的資源,需要使用不同的Resource實現(xiàn)類,比較麻煩,可以在不顯式使用具體Resource實現(xiàn)類的情況下,通過資源地址的特殊標識(如“classpath:”、“file:”)就可以訪問到資源。
資源地址表達式
地址前綴: classpath:
示例:classpath:com/hqq/bean.xml
對應(yīng)的資源類型:從類路徑中加載資源,可以在文件系統(tǒng) 中,也 可以在JAR或ZIP的類包中。
地址前綴:file:
示例:file:/com/hqq/bean.xml
對應(yīng)的資源類型:使用UrlResource從文件系統(tǒng)中加載資源,可采用絕對或相對路徑。
地址前綴:http://
示例:http://www.hqq.com/bean.xml
對應(yīng)的資源類型:使用UrlResource從web服務(wù)器中加載資源。
地址前綴:ftp://
示例:file://www.hqq.com/bean.xml
對應(yīng)的資源類型:使用UrlResource從FTP服務(wù)器中加載資源。
地址前綴:沒有前綴
示例:com/hqq/bean.xml
對應(yīng)的資源類型:根據(jù)ApplicationContext的具體實現(xiàn)采用對應(yīng)類型的Resource來加載
“classpath:”與“classpath*:”的區(qū)別:
如果有多個JAR包或文件系統(tǒng)類路徑都有相同的包名(如 com.hqq),“classpath:”只會在第一個加載的com.hqq包的類路徑下查找資源。而“classpath*:”會掃描所有這些JAR包及類路徑下出現(xiàn)的com.hqq類路徑。
Ant風(fēng)格的資源地址支持3種匹配符:
?:匹配文件名中一個字符。如 classpath:com/h?q/bean.xml
*:匹配文件名中的任意字符。如 classpath:com/hqq/*.xml
**:匹配多層路徑。如 classpath:com/*/.xml
資源加載器
ResourceLoad接口僅有一個getResource(String location)方法,可以根據(jù)一個資源地址加載文件資源,只支持帶資源類型前綴的表達式,不支持Ant風(fēng)格的資源表達式。ResourcePatternResolver接口擴展了ResourceLoader接口,支持Ant風(fēng)格表達式。PathMatchingResourcePatternResolver是spring提供的標準實現(xiàn)類。
資源加載DEMO
package com.hqq.spring.resourceload;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import java.io.IOException;
/**
* 測試spring資源加載DEMO
* Created by HUANGQIQIN on 2018/9/15.
*/
public class TestSpringResourceLoad {
public static void main(String[] args) {
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
try {
//加載所有類包com.hqq下的xml文件
Resource[] resources = resolver.getResources("classpath*:com/hqq/**/*.xml");
for (Resource resource : resources){
System.out.println(resource.getDescription());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
運行結(jié)果:
file [F:\ideawork\hqqstudy\springstudy\target\classes\com\hqq\spring\resourceload\application-spring.xml]