Java Spring类路径前缀差异

Java Spring类路径前缀差异,java,spring,classpath,Java,Spring,Classpath,文件化it声明 此特殊前缀指定所有 与 必须获取给定的名称 (在内部,这基本上是发生的 通过ClassLoader.getResources(…) 调用),然后合并以形成 最终的应用程序上下文定义 有人能解释一下吗 使用classpath*:conf/appContext.xml与不带星号的classpath:conf/appContext.xml有什么区别。当您想使用通配符语法从多个bean定义文件构建应用程序上下文时,classpath*:…语法非常有用 例如,如果您使用classpath*

文件化it声明

此特殊前缀指定所有 与 必须获取给定的名称 (在内部,这基本上是发生的 通过ClassLoader.getResources(…) 调用),然后合并以形成 最终的应用程序上下文定义

有人能解释一下吗


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

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

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


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

简单定义

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


相反,
classpath:conf/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)};
      }
   }
}  

他们之间还有一个有趣的区别。请看我的问题:一件非常重要的事情——如果您使用*并且Spring没有找到匹配项,它不会抱怨。如果不使用*并且没有匹配项,上下文将不会启动(!)classpath*是否也会在子目录中查找?换句话说,如果我在类路径根中有appContext.xml,在/dir/appContext.xml中有一个,那么当我使用classpath*:appContext.xml时,它会同时加载这两个文件吗?“不可能使用classpath*:前缀来构造实际的
资源,因为一个资源一次只指向一个资源。”另外,我刚刚遇到了一个奇怪的错误,这就是我最终出现在这里的原因。若您要导入资源,那个么使用通配符类路径前缀是并没有意义的。将来的读者也会看到这个错误,带有“status=depended”。为了防止URL最终失败,错误帖子的标题是“使用通配符类路径和通配符路径从JAR文件的根导入XML文件不起作用[SPR-11390]”,您能解释一下吗?