spring中resource是一個接口,為資源的抽象提供了一套操作方式颅悉,可匹配類似于classpath:XXX,file://XXX等不同協(xié)議的資源訪問隧土。
如上圖所示鹿榜,spring已經(jīng)提供了多種訪問資源的實體類,還有DefaultResourceLoader類土匀,使得與具體的context結(jié)合子房。在spring中根據(jù)設(shè)置的配置文件路徑轉(zhuǎn)換為對應(yīng)的文件資源
// AbstractBeanDefinitionReader 文件
Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
// DefaultResourceLoader 文件
public Resource getResource(String location) {
Assert.notNull(location, "Location must not be null");
for (ProtocolResolver protocolResolver : this.protocolResolvers) {
Resource resource = protocolResolver.resolve(location, this);
if (resource != null) {
return resource;
}
}
if (location.startsWith("/")) {
// ClassPathContextResource
return getResourceByPath(location);
}
else if (location.startsWith(CLASSPATH_URL_PREFIX)) {
return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
// 如果是以classpath:開頭,認(rèn)為是classpath樣式的資源,返回ClassPathResource
}
else {
try {
URL url = new URL(location);
return new UrlResource(url);
// 符合URL協(xié)議池颈,返回UrlResource
}
catch (MalformedURLException ex) {
return getResourceByPath(location);
// 剩下的無法判斷的全部返回ClassPathContextResource
}
}
}
// 然后在真正的使用resource的文件流時尾序,XmlBeanDefinitionReader文件內(nèi)
InputStream inputStream = encodedResource.getResource().getInputStream();
有多種具體的Resource類的獲取輸入流的實現(xiàn)方式。
FileSystemResource 類
public InputStream getInputStream() throws IOException {
return new FileInputStream(this.file);
// this.file 是個File對象
}
ClassPathContextResource和ClassPathResource的獲取IO流的方法是同一個
現(xiàn)在基本上清楚了spring針對不同協(xié)議的文件路徑是如何操作路徑躯砰,以什么樣子的方式獲取IO流每币,不過還是有幾個疑問需要深入了解下。
- 如何匹配多個資源文件
- FileSystemXmlApplicationContext和ClassPathXmlApplicationContext的區(qū)別
匹配多個資源文件
之前說的例子都是明確指定context.xml 的情況琢歇,可是現(xiàn)實中會配置多個配置文件兰怠,然后依次加載,例如*.xml會匹配當(dāng)前目錄下面所有的.xml
文件李茫。來到了PathMatchingResourcePatternResolver.class匹配出多個xml的情況
至于為什么會定位到PathMatchingResourcePatternResolver.class這個文件揭保,可以看
AbstractApplicationContext 文件
public AbstractApplicationContext() {
this.resourcePatternResolver = getResourcePatternResolver();
}
protected ResourcePatternResolver getResourcePatternResolver() {
return new PathMatchingResourcePatternResolver(this);
}
// 也就意味著在context類初始化的時候,就直接設(shè)置了好了resourcePatternResolver對象為PathMatchingResourcePatternResolver
PathMatchingResourcePatternResolver 文件
public Resource[] getResources(String locationPattern) throws IOException {
Assert.notNull(locationPattern, "Location pattern must not be null");
if (locationPattern.startsWith(CLASSPATH_ALL_URL_PREFIX)) {
// 通過classpath:開頭的地址
if (getPathMatcher().isPattern(locationPattern.substring(CLASSPATH_ALL_URL_PREFIX.length()))) {
// 地址路徑中包含了 【*】這個匹配的關(guān)鍵字魄宏,意味著要模糊匹配
return findPathMatchingResources(locationPattern);
}
else {
// 查找當(dāng)前所有的classpath資源并返回
return findAllClassPathResources(locationPattern.substring(CLASSPATH_ALL_URL_PREFIX.length()));
}
}
else {
// and on Tomcat only after the "*/" separator for its "war:" protocol.
int prefixEnd = (locationPattern.startsWith("war:") ? locationPattern.indexOf("*/") + 1 :
locationPattern.indexOf(":") + 1);
if (getPathMatcher().isPattern(locationPattern.substring(prefixEnd))) {
// 除去前綴秸侣,包含【*】,進(jìn)行模糊匹配
return findPathMatchingResources(locationPattern);
}
else {
// 這個是針對具體的xml文件的匹配規(guī)則,會進(jìn)入到DefaultResourceLoader裝載資源文件
return new Resource[] {getResourceLoader().getResource(locationPattern)};
}
}
}
// 根據(jù)模糊地址找出所有匹配的資源文件
protected Resource[] findPathMatchingResources(String locationPattern) throws IOException {
String rootDirPath = determineRootDir(locationPattern);
// 根路徑宠互,此處為xml/
String subPattern = locationPattern.substring(rootDirPath.length());
// 子路徑味榛,此處為*.xml
Resource[] rootDirResources = getResources(rootDirPath);
// 調(diào)用本身,算出根路徑的資源信息
// 如果為xml/*.xml 則返回一個根路徑資源信息xml/
// 如果為xml/**/*.xml 則還是返回一組根路徑資源信息xml/
Set<Resource> result = new LinkedHashSet<Resource>(16);
for (Resource rootDirResource : rootDirResources) {
rootDirResource = resolveRootDirResource(rootDirResource);
URL rootDirURL = rootDirResource.getURL();
// 獲取其URL信息
if (equinoxResolveMethod != null) {
if (rootDirURL.getProtocol().startsWith("bundle")) {
rootDirURL = (URL) ReflectionUtils.invokeMethod(equinoxResolveMethod, null, rootDirURL);
rootDirResource = new UrlResource(rootDirURL);
}
}
if (rootDirURL.getProtocol().startsWith(ResourceUtils.URL_PROTOCOL_VFS)) {
// jboss的文件協(xié)議
result.addAll(VfsResourceMatchingDelegate.findMatchingResources(rootDirURL, subPattern, getPathMatcher()));
}
else if (ResourceUtils.isJarURL(rootDirURL) ||
isJarResource(rootDirResource)) {
// jar包
result.addAll(doFindPathMatchingJarResources(rootDirResource, rootDirURL, subPattern));
}
else {
// 默認(rèn)掃描當(dāng)前的所有資源予跌,添加到result中
result.addAll(doFindPathMatchingFileResources(rootDirResource, subPattern));
}
}
if (logger.isDebugEnabled()) {
logger.debug("Resolved location pattern [" + locationPattern + "] to resources " + result);
}
return result.toArray(new Resource[result.size()]);
}
// 通過路徑去匹配到合適的資源搏色,此處的rootDir包含了絕對路徑
protected Set<File> retrieveMatchingFiles(File rootDir, String pattern)
throws IOException {
if (!rootDir.exists()) {
// 根路徑都不存在,則返回空
if (logger.isDebugEnabled()) {
logger.debug("Skipping [" + rootDir.getAbsolutePath() + "] because it does not exist");
}
return Collections.emptySet();
}
if (!rootDir.isDirectory()) {
// 不是文件夾券册,返回空
if (logger.isWarnEnabled()) {
logger.warn("Skipping [" + rootDir.getAbsolutePath() + "] because it does not denote a directory");
}
return Collections.emptySet();
}
if (!rootDir.canRead()) {
// 文件不可讀频轿,也返回空
if (logger.isWarnEnabled()) {
logger.warn("Cannot search for matching files underneath directory [" + rootDir.getAbsolutePath() +
"] because the application is not allowed to read the directory");
}
return Collections.emptySet();
}
String fullPattern = StringUtils.replace(rootDir.getAbsolutePath(), File.separator, "/");
// 得到當(dāng)前系統(tǒng)下的文件絕對地址
if (!pattern.startsWith("/")) {
fullPattern += "/";
}
fullPattern = fullPattern + StringUtils.replace(pattern, File.separator, "/");
// 得到完整的全路徑 例如/user/...*.xml
Set<File> result = new LinkedHashSet<File>(8);
doRetrieveMatchingFiles(fullPattern, rootDir, result);
// 得到當(dāng)前rootDir下面的所有文件,然后配合fullPattern進(jìn)行匹配烁焙,得到的結(jié)果在result中
return result;
}
protected void doRetrieveMatchingFiles(String fullPattern, File dir, Set<File> result) throws IOException {
if (logger.isDebugEnabled()) {
logger.debug("Searching directory [" + dir.getAbsolutePath() +
"] for files matching pattern [" + fullPattern + "]");
}
File[] dirContents = dir.listFiles();
// 得到當(dāng)前根路徑的所有文件(包含了文件夾)
if (dirContents == null) {
if (logger.isWarnEnabled()) {
logger.warn("Could not retrieve contents of directory [" + dir.getAbsolutePath() + "]");
}
return;
}
Arrays.sort(dirContents);
// 這個也需要注意到航邢,這個順序決定了掃描文件的先后順序,也意味著bean加載的情況
for (File content : dirContents) {
String currPath = StringUtils.replace(content.getAbsolutePath(), File.separator, "/");
if (content.isDirectory() && getPathMatcher().matchStart(fullPattern, currPath + "/")) {
// 如果是文件夾骄蝇,類似于xml/**/*.xml 文件
// 訪問到了** 就會是文件夾
if (!content.canRead()) {
...
}
else {
// 循環(huán)迭代訪問文件
doRetrieveMatchingFiles(fullPattern, content, result);
}
}
if (getPathMatcher().match(fullPattern, currPath)) {
result.add(content);
// 匹配完成翠忠,添加到結(jié)果集合中
}
}
}
這樣整個的xml文件讀取過程就全部完成,也清楚了實際中xml文件是什么樣的形式被訪問到的乞榨。
其實spring的路徑風(fēng)格是和Apache Ant的路徑樣式一樣的秽之,Ant的更多細(xì)節(jié)可以自行學(xué)習(xí)了解。
FileSystemXmlApplicationContext和ClassPathXmlApplicationContext的區(qū)別
這個看名字就很明顯吃既,就是加載文件不太一樣考榨,一個通過純粹的文件協(xié)議去訪問,另一個卻可以兼容多種協(xié)議鹦倚。仔細(xì)分析他們的差異河质,會發(fā)現(xiàn)主要的差異就在于FileSystemXmlApplicationContext重寫的getResourceByPath方法
FileSystemXmlApplicationContext 文件
protected Resource getResourceByPath(String path) {
if (path != null && path.startsWith("/")) {
path = path.substring(1);
}
return new FileSystemResource(path);
}
上面代碼學(xué)習(xí),已經(jīng)清楚了在默認(rèn)的中是生成ClassPathContextResource資源,但是重寫之后意味著被強制性的設(shè)置為了FileSystemResource掀鹅,就會出現(xiàn)文件不存在的情況散休。
如下圖,設(shè)置的path只有context.xml
乐尊,就會被提示找不到文件戚丸,因為此時的文件路徑是項目路徑 + context.xml
如果改為使用simple-spring-demo/src/main/resources/context.xml
,此時需要注意修改xml內(nèi)的properties文件路徑扔嵌,否則也會提示文件找不到
這樣就符合設(shè)置了限府,運行正常,這也告訴我們一旦使用FileSystemXmlApplicationContext記得修改所有的路徑配置痢缎,以防止出現(xiàn)文件找不到的錯誤胁勺。