Spring classpath前缀差异

问题描述 投票:131回答:4

记录的here它说

此特殊前缀指定必须获取与给定名称匹配的所有类路径资源(内部,这通常通过ClassLoader.getResources(...)调用),然后合并以形成最终的应用程序上下文定义。

有人可以解释一下吗?

使用classpath*:conf/appContext.xml而不是没有星号的classpath:conf/appContext.xml有什么区别。

java spring classpath
4个回答
198
投票

简单的定义

classpath*:conf/appContext.xml只是意味着类路径中所有jar中的conf文件夹下的所有appContext.xml文件都将被拾取并加入到一个大的应用程序上下文中。

相比之下,classpath:conf/appContext.xml只会加载一个这样的文件......第一个在类路径中找到。


38
投票

当您希望使用通配符语法从多个bean定义文件构建应用程序上下文时,classpath*:...语法非常有用。

例如,如果使用classpath*:appContext.xml构造上下文,则将针对类路径中名为appContext.xml的每个资源扫描类路径,并将所有资源中的bean定义合并到单个上下文中。

相比之下,classpath:conf/appContext.xml将从类路径中获取一个且仅有一个名为appContext.xml的文件。如果有多个,其他人将被忽略。


21
投票

classpath *:它引用资源列表并加载类路径和列表中存在的所有此类文件可以为空,如果类路径中不存在此类文件,则应用程序不会抛出任何异常(只是忽略错误)。

classpath:它引用某个资源并仅加载在类路径中找到的第一个文件,如果类路径中没有这样的文件,它将引发异常

java.io.FileNotFoundException: class path resource [conf/appContext.xml] cannot be opened because it does not exist

0
投票

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)};
      }
   }
}  
© www.soinside.com 2019 - 2024. All rights reserved.