Spring classpath前缀差异

时间:2010-07-20 21:16:16

标签: java spring classpath

记录here它陈述

  

此特殊前缀指定所有   与之匹配的classpath资源   必须获得给定的名称   (内部,这基本上发生了   通过ClassLoader.getResources(...)   调用),然后合并形成   最终的应用程序上下文定义。

有人可以解释一下吗?

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

4 个答案:

答案 0 :(得分:195)

SIMPLE DEFINITION

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

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

答案 1 :(得分:37)

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

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

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

答案 2 :(得分:19)

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

classpath 它指的是某个资源只会加载在类路径中找到的第一个文件,如果没有这样的文件则在类路径中它将引发异常

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

答案 3 :(得分: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)};
      }
   }
}