在《深入spring ioc源码之resource》中已经详细介绍了spring中resource的抽象,resource接口有很多实现类,我们当然可以使用各自的构造函数创建符合需求的resource实例,然而spring提供了resourceloader接口用于实现不同的resource加载策略,即将不同resource实例的创建交给resourceloader来计算。
public interface resourceloader {
//classpath
string classpath_url_prefix = resourceutils.classpath_url_prefix;
resource getresource(string location);
classloader getclassloader();
}
在resourceloader接口中,主要定义了一个方法:getresource(),它通过提供的资源location参数获取resource实例,该实例可以是claspathresource、filesystemresource、urlresource等,但是该方法返回的resource实例并不保证该resource一定是存在的,需要调用exists方法判断。该方法需要支持一下模式的资源加载:
1. url位置资源,如”file:c:/test.dat”
2. classpath位置资源,如”classpath:test.dat”
3. 相对路径资源,如”web-inf/test.dat”,此时返回的resource实例根据实现不同而不同。
resourceloader接口还提供了getclassloader()方法,在加载classpath下的资源时作为参数传入classpathresource。将classloader暴露出来,对于想要获取resourceloader使用的classloader用户来说,可以直接调用getclassloader()方法获得,而不是依赖于thread context classloader,因为有些时候resourceloader内部使用自定义的classloader。
在实际开发中经常会遇到需要通过某种匹配方式查找资源,而且可能有多个资源匹配这种模式,在spring中提供了resourcepatternresolver接口用于实现这种需求,该接口继承自resourceloader接口,定义了自己的模式匹配接口:
public interface resourcepatternresolver extends resourceloader {
string classpath_all_url_prefix = "classpath*:";
resource[] getresources(string locationpattern) throws ioexception;
resourcepatternresolver定义了getresources()方法用于根据传入的locationpattern查找和其匹配的resource实例,并以数组的形式返回,在返回的数组中不可以存在相同的resource实例。resourcepatternresolver中还定义了”classpath*:”模式,用于表示查找classpath下所有的匹配resource。
在spring中,对resourceloader提供了defaultresourceloader、filesystemresourceloader和servletcontextresourceloader等单独实现,对resourcepatternresolver接口则提供了pathmatchingresourcepatternresolver实现。并且applicationcontext接口继承了resourcepatternresolver,在实现中,applicationcontext的实现类会将逻辑代理给相关的单独实现类,如pathmatchingresourceloader等。在applicationcontext中resourceloaderaware接口,可以将resourceloader(自身)注入到实现该接口的bean中,在bean中可以将其强制转换成resourcepatternresolver接口使用(为了安全,强转前需要判断)。在spring中对resourceloader相关类的类图如下:
defaultresourceloader是resourceloader的默认实现,abstractapplicationcontext继承该类(关于这个继承,简单吐槽一下,spring内部感觉有很多这种个人感觉使用组合更合适的继承,比如还有abstractbeanfactory继承自factorybeanregisterysupport,这个让我看起来有点不习惯,而且也增加了类的继承关系)。它接收classloader作为构造函数的参数,或使用不带参数的构造函数,此时classloader使用默认的classloader(一般为thread context classloader),classloader也可以通过set方法后继设置。
其最主要的逻辑实现在getresource方法中,该方法首先判断传入的location是否以”classpath:”开头,如果是,则创建classpathresource(移除”classpath:”前缀),否则尝试创建urlresource,如果当前location没有定义url的协议(即以”file:”、”zip:”等开头,比如使用相对路径”resources/meta-inf/menifest.mf),则创建urlresource会抛出malformedurlexception,此时调用getresourcebypath()方法获取resource实例。getresourcebypath()方法默认返回classpathcontextresource实例,在filesystemresourceloader中有不同实现。
public resource getresource(string location) {
assert.notnull(location, "location must not be null");
if (location.startswith(classpath_url_prefix)) {
return new classpathresource(location.substring(classpath_url_prefix.length()), getclassloader());
}
else {
try {
// try to parse the location as a url...
url url = new url(location);
return new urlresource(url);
}
catch (malformedurlexception ex) {
// no url -> resolve as resource path.
return getresourcebypath(location);
protected resource getresourcebypath(string path) {
return new classpathcontextresource(path, getclassloader());
filesystemresourceloader继承自defaultresourceloader,它的getresource方法的实现逻辑和defaultresourceloader相同,不同的是它实现了自己的getresourcebypath方法,即当urlresource创建失败时,它会使用filesystemcontextresource实例而不是classpathcontextresource:
if (path != null && path.startswith("/")) {
path = path.substring(1);
return new filesystemcontextresource(path);
使用该类时要特别注意的一点:即使location以”/”开头,资源的查找还是相对于vm启动时的相对路径而不是绝对路径(从以上代码片段也可以看出,它会先截去开头的”/”),这个和servlet container保持一致。如果需要使用绝对路径,需要添加”file:”前缀。
servletcontextresourceloader类继承自defaultresourceloader,和filesystemresourceloader一样,它的getresource方法的实现逻辑和defaultresourceloader相同,不同的是它实现了自己的getresourcebypath方法,即当urlresource创建失败时,它会使用servletcontextresource实例:
return new servletcontextresource(this.servletcontext, path);
这里的path即使以”/”开头,也是相对servletcontext的路径,而不是绝对路径,要使用绝对路径,需要添加”file:”前缀。
pathmatchingresourcepatternresolver类实现了resourcepatternresolver接口,它包含了对resourceloader接口的引用,在对继承自resourceloader接口的方法的实现会代理给该引用,同时在getresources()方法实现中,当找到一个匹配的资源location时,可以使用该引用解析成resource实例。默认使用defaultresourceloader类,用户可以使用构造函数传入自定义的resourceloader。
pathmatchingresourcepatternresolver还包含了一个对pathmatcher接口的引用,该接口基于路径字符串实现匹配处理,如判断一个路径字符串是否包含通配符(’*’、’?’),判断给定的path是否匹配给定的pattern等。spring提供了antpathmatcher对pathmatcher的默认实现,表达该pathmatcher是采用ant风格的实现。其中pathmatcher的接口定义如下:
public interface pathmatcher {
boolean ispattern(string path);
boolean match(string pattern, string path);
boolean matchstart(string pattern, string path);
string extractpathwithinpattern(string pattern, string path);
ispattern(string path):
判断path是否是一个pattern,即判断path是否包含通配符:
public boolean ispattern(string path) {
return (path.indexof('*') != -1 || path.indexof('?') != -1);
match(string pattern, string path):
判断给定path是否可以匹配给定pattern:
matchstart(string pattern, string path):
判断给定path是否可以匹配给定pattern,该方法不同于match,它只是做部分匹配,即当发现给定path匹配给定path的可能性比较大时,即返回true。在pathmatchingresourcepatternresolver中,可以先使用它确定需要全面搜索的范围,然后在这个比较小的范围内再找出所有的资源文件全路径做匹配运算。
在antpathmatcher中,都使用domatch方法实现,match方法的fullmatch为true,而matchstart的fullmatch为false:
protected boolean domatch(string pattern, string path, boolean fullmatch)
domatch的基本算法如下:
1. 检查pattern和path是否都以”/”开头或者都不是以”/”开头,否则,返回false。
2. 将pattern和path都以”/”为分隔符,分割成两个字符串数组pattarray和patharray。
3. 从头遍历两个字符串数组,如果遇到两给字符串不匹配(两个字符串的匹配算法再下面介绍),返回false,否则,直到遇到pattarray中的”**”字符串,或pattarray和patharray中有一个遍历完。
4. 如果pattarray遍历完:
a) patharray也遍历完,并且pattern和path都以”/”结尾或都不以”/”,返回true,否则返回false。
b) pattarray没有遍历完,但fullmatch为false,返回true。
c) pattarray只剩最后一个”*”,同时path以”/”结尾,返回true。
d) pattarray剩下的字符串都是”**”,返回true,否则返回false。
5. 如果patharray没有遍历完,而pattarray遍历完了,返回false。
6. 如果patharray和pattarray都没有遍历完,fullmatch为false,而且pattarray下一个字符串为”**”时,返回true。
7. 从后开始遍历patharray和pattarray,如果遇到两个字符串不匹配,返回false,否则,直到遇到pattarray中的”**”字符串,或patharray和pattarray中有一个和之前的遍历索引相遇。
8. 如果是因为patharray与之前的遍历索引相遇,此时,如果没有遍历完的pattarray所有字符串都是”**”,则返回true,否则,返回false。
9. 如果patharray和pattarray中间都没有遍历完:
a) 去除pattarray中相邻的”**”字符串,并找到其下一个”**”字符串,其索引号为pattidxtmp,他们的距离即为s
b) 从剩下的patharray中的第i个元素向后查找s个元素,如果找到所有s个元素都匹配,则这次查找成功,记i为temp,如果没有找到这样的s个元素,返回false。
c) 将pattarray的起始索引设置为pattidxtmp,将patharray的索引号设置为temp+s,继续查找,直到pattarray或patharray遍历完。
10. 如果pattarray没有遍历完,但剩下的元素都是”**”,返回true,否则返回false。
对路径字符串数组中的字符串匹配算法如下:
1. 记pattern为模式字符串,str为要匹配的字符串,将两个字符串转换成两个字符数组pattarray和strarray。
2. 遍历pattarray直到遇到’*’字符。
3. 如果pattarray中不存在’*’字符,则只有在pattarray和strarray的长度相同两个字符数组中所有元素都相同,其中pattarray中的’?’字符可以匹配strarray中的任何一个字符,否则,返回false。
4. 如果pattarray只包含一个’*’字符,返回true
5. 遍历pattarray和strarray直到pattarray遇到’*’字符或strarray遍历完,如果存在不匹配的字符,返回false。
6. 如果因为strarray遍历完成,而pattarray剩下的字符都是’*’,返回true,否则返回false
7. 从末尾开始遍历pattarray和strarray,直到pattarray遇到’*’字符,或strarray遇到之前的遍历索引,中间如果遇到不匹配字符,返回false
8. 如果strarray遍历完,而剩下的pattarray字符都是’*’字符,返回true,否则返回false
9. 如果pattarray和strarray都没有遍历完(类似之前的算法):
a) 去除pattarray相邻的’*’字符,查找下一个’*’字符,记其索引号为pattidxtmp,两个’*’字符的相隔距离为s
b) 从剩下的strarray中的第i个元素向后查找s个元素,如果有找到所有s个元素都匹配,则这次查找成功,记i为temp,如果没有到这样的s个元素,返回false。
c) 将pattarray的起始索引设置为pattidxtmp,strarray的起始索引设置为temp+s,继续查找,直到pattarray或strarray遍历完。
10. 如果pattarray没有遍历完,但剩下的元素都是’*’,返回true,否则返回false
string extractpathwithinpattern(string pattern, string path):
去除path中和pattern相同的字符串,只保留匹配的字符串。比如如果pattern为”/doc/csv/*.htm”,而path为”/doc/csv/commit.htm”,则该方法的返回值为commit.htm。该方法默认pattern和path已经匹配成功,因而算法比较简单:
以’/’分割pattern和path为两个字符串数组pattarray和patharray,遍历pattarray,如果该字符串包含’*’或’?’字符,则并且patharray的长度大于当前索引号,则将该字符串添加到结果中。
遍历完pattarray后,如果patharray长度大于pattarray,则将剩下的patharray都添加到结果字符串中。
最后返回该字符串。
不过也正是因为该算法实现比较简单,因而它的结果貌似不那么准确,比如pattern的值为:/com/**/levin/**/commit.html,而path的值为:/com/citi/cva/levin/html/commit.html,其返回结果为:citi/levin/commit.html
现在言归正传,看一下pathmatchingresourcepatternresolver中的getresources方法的实现:
public resource[] getresources(string locationpattern) throws ioexception {
assert.notnull(locationpattern, "location pattern must not be null");
if (locationpattern.startswith(classpath_all_url_prefix)) {
// a class path resource (multiple resources for same name possible)
if (getpathmatcher().ispattern(locationpattern.substring(classpath_all_url_prefix.length()))) {
// a class path resource pattern
return findpathmatchingresources(locationpattern);
else {
// all class path resources with the given name
return findallclasspathresources(locationpattern.substring(classpath_all_url_prefix.length()));
// only look for a pattern after a prefix here
// (to not get fooled by a pattern symbol in a strange prefix).
int prefixend = locationpattern.indexof(":") + 1;
if (getpathmatcher().ispattern(locationpattern.substring(prefixend))) {
// a file pattern
// a single resource with the given name
return new resource[] {getresourceloader().getresource(locationpattern)};
对classpath下的资源,相同名字的资源可能存在多个,如果使用”classpath*:”作为前缀,表明需要找到classpath下所有该名字资源,因而需要调用findclasspathresources方法查找classpath下所有该名称的resource,对非classpath下的资源,对于不存在模式字符的location,一般认为一个location对应一个资源,因而直接调用resourceloader.getresource()方法即可(对classpath下没有以”classpath*:”开头的location也适用)。
findclasspathresources方法实现相对比较简单:
适用classloader.getresources()方法,遍历结果url集合,将每个结果适用urlresource封装,最后组成一个resource数组返回即可。
对包含模式匹配字符的location来说,需要调用findpathmatchingresources方法:
protected resource[] findpathmatchingresources(string locationpattern) throws ioexception {
string rootdirpath = determinerootdir(locationpattern);
string subpattern = locationpattern.substring(rootdirpath.length());
resource[] rootdirresources = getresources(rootdirpath);
set result = new linkedhashset(16);
for (int i = 0; i < rootdirresources.length; i++) {
resource rootdirresource = resolverootdirresource(rootdirresources[i]);
if (isjarresource(rootdirresource)) {
result.addall(dofindpathmatchingjarresources(rootdirresource, subpattern));
result.addall(dofindpathmatchingfileresources(rootdirresource, subpattern));
if (logger.isdebugenabled()) {
logger.debug("resolved location pattern [" + locationpattern + "] to resources " + result);
return (resource[]) result.toarray(new resource[result.size()]);
1. determinrootdir()方法返回locationpattern中最长的没有出现模式匹配字符的路径
2. subpattern则表示rootdirpath之后的包含模式匹配字符的路径信pattern
3. 使用getresources()获取rootdirpath下的所有资源数组。
4. 遍历这个数组。
a) 对jar中的资源,使用dofindpathmatchingjarresources()方法来查找和匹配。
b) 对非jar中资源,使用dofindpathmatchingfileresources()方法来查找和匹配。
dofindpathmatchingjarresources()实现:
1. 计算当前resource在jar文件中的根路径rootentrypath。
2. 遍历jar文件中所有entry,如果当前entry名以rootentrypath开头,并且之后的路径信息和之前从patternlocation中截取出的subpattern使用pathmatcher匹配,若匹配成功,则调用rootdirresource.createrelative方法创建一个resource,将新创建的resource添加入结果集中。
dofindpathmatchingfileresources()实现:
1. 获取要查找资源的根路径(根路径全名)
2. 递归获得根路径下的所有资源,使用pathmatcher匹配,如果匹配成功,则创建filesystemresource,并将其加入到结果集中。在递归进入一个目录前首先调用pathmatcher.matchstart()方法,以先简单的判断是否需要递归进去,以提升性能。
protected void doretrievematchingfiles(string fullpattern, file dir, set result) throws ioexception {
logger.debug("searching directory [" + dir.getabsolutepath() +
"] for files matching pattern [" + fullpattern + "]");
file[] dircontents = dir.listfiles();
if (dircontents == null) {
throw new ioexception("could not retrieve contents of directory [" + dir.getabsolutepath() + "]");
for (int i = 0; i < dircontents.length; i++) {
file content = dircontents[i];
string currpath = stringutils.replace(content.getabsolutepath(), file.separator, "/");
if (content.isdirectory() && getpathmatcher().matchstart(fullpattern, currpath + "/")) {
doretrievematchingfiles(fullpattern, content, result);
if (getpathmatcher().match(fullpattern, currpath)) {
result.add(content);
最后,需要注意的是,由于classloader.getresources()方法存在的限制,当传入一个空字符串时,它只能从classpath的文件目录下查找,而不会从jar文件的根目录下查找,因而对”classpath*:”前缀的资源来说,找不到jar根路径下的资源。即如果我们有以下定义:”classpath*:*.xml”,如果只有在jar文件的根目录下存在*.xml文件,那么这个pattern将返回空的resource数组。解决方法是不要再jar文件根目录中放文件,可以将这些文件放到jar文件中的resources、config等目录下去。并且也不要在”classpath*:”之后加一些通配符,如”classpath*:**/*enum.class”,至少在”classpath*:”后加入一个不存在通配符的路径名。
servletcontextresourcepatternresolver类继承自pathmatchingresourcepatternresolver类,它重写了父类的文件查找逻辑,即对servletcontextresource资源使用servletcontext.getresourcepaths()方法来查找参数目录下的文件,而不是file.listfiles()方法:
protected set dofindpathmatchingfileresources(resource rootdirresource, string subpattern) throws ioexception {
if (rootdirresource instanceof servletcontextresource) {
servletcontextresource scresource = (servletcontextresource) rootdirresource;
servletcontext sc = scresource.getservletcontext();
string fullpattern = scresource.getpath() + subpattern;
set result = new linkedhashset(8);
doretrievematchingservletcontextresources(sc, fullpattern, scresource.getpath(), result);
return result;
return super.dofindpathmatchingfileresources(rootdirresource, subpattern);
在abstractapplicationcontext中,对resourcepatternresolver的实现只是简单的将getresources()方法的实现代理给resourcepatternresolver字段,而该字段默认在abstractapplicationcontext创建时新建一个pathmatchingresourcepatternresolver实例:
public abstractapplicationcontext(applicationcontext parent) {
this.parent = parent;
this.resourcepatternresolver = getresourcepatternresolver();
protected resourcepatternresolver getresourcepatternresolver() {
return new pathmatchingresourcepatternresolver(this);
return this.resourcepatternresolver.getresources(locationpattern);