在4.7.2.2 The classpath*: prefix中记录了以下内容:
这个特殊的前缀指定了所有与给定名称匹配的类路径资源必须被获取(内部上,这基本上是通过ClassLoader.getResources(...)调用来实现的),然后合并以形成最终的应用程序上下文定义。
有人能解释一下吗?
使用classpath*:conf/appContext.xml
和不带星号的classpath:conf/appContext.xml
之间有什么区别?
在4.7.2.2 The classpath*: prefix中记录了以下内容:
这个特殊的前缀指定了所有与给定名称匹配的类路径资源必须被获取(内部上,这基本上是通过ClassLoader.getResources(...)调用来实现的),然后合并以形成最终的应用程序上下文定义。
有人能解释一下吗?
使用classpath*:conf/appContext.xml
和不带星号的classpath:conf/appContext.xml
之间有什么区别?
简单定义
classpath*:conf/appContext.xml
简单来说,就是在类路径下的所有jar包中位于 conf
文件夹下的所有 appContext.xml 文件都会被读取并整合成一个大的应用程序上下文。
相反,classpath:conf/appContext.xml
只会加载第一个被找到的文件...其余的将被忽略。
classpath*:...
语法主要用于从多个 bean 定义文件构建应用程序上下文,使用通配符语法。
例如,如果你使用 classpath*:appContext.xml
构建上下文,类路径将会扫描所有名为 appContext.xml
的资源,并将所有文件的 bean 定义合并到一个上下文中。
相比之下,classpath:conf/appContext.xml
只会在类路径中获取一个名为 appContext.xml
的文件。如果有多个文件,则其它文件将被忽略。
java.io.FileNotFoundException:
class path resource [conf/appContext.xml] cannot be opened because it does not exist
Spring的源代码:
public Resource[] getResources(String locationPattern) throws IOException {
Assert.notNull(locationPattern, "Location pattern must not be null");
//CLASSPATH_ALL_URL_PREFIX="classpath*:"
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()));
}
}
else {
// 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
return findPathMatchingResources(locationPattern);
}
else {
// a single resource with the given name
return new Resource[] {getResourceLoader().getResource(locationPattern)};
}
}
}