9

我有这个非常简单的课程:

 @RunWith(SpringJUnit4ClassRunner.class)
 @ContextConfiguration(locations={"classpath*:/application-context-this-does-not-exist.xml"})
  public class HTMLSourceExtractorImplTest {

    @Autowired
    ApplicationContext context;

    @Test
    public void test(){
         String [] beans = context.getBeanDefinitionNames();
             for(String bean : beans){
                 System.out.println(bean);
             }
         System.out.println("Testing");
    }
}

在类路径中指定的这个上下文文件不存在。我几乎可以输入任何我想要的名称,并且代码不会中断。我的意思是测试运行得很好,就好像那个文件真的存在一样。

如果我做一个小的改变,从 : classpath*classpath,然后它会发出喙,说这个文件不存在,这也是我在第一种情况下所期望的行为。

春季版本 3.2.3.RELEASE。

有人可以解释这种奇怪的行为吗?

编辑

建议的日志中的内容:

     20:47:26,923 INFO  [GenericApplicationContext] Refreshing org.springframework.context.support.GenericApplicationContext@3df6c65c: startup date [Fri Jun 07 20:47:26 PDT 2013]; root of context hierarchy

我什至尝试从应用程序上下文中输出所有 bean:

  org.springframework.context.annotation.internalConfigurationAnnotationProcessor
  org.springframework.context.annotation.internalAutowiredAnnotationProcessor
  org.springframework.context.annotation.internalRequiredAnnotationProcessor
  org.springframework.context.annotation.internalCommonAnnotationProcessor                   
  org.springframework.context.annotation.ConfigurationClassProcessor.importAwareProcessor

在我看来,如果是通配符,Spring 将创建一个默认的空应用程序上下文

4

1 回答 1

19

JavaDoc 中的引用可能会回答您的问题:

/**
 * Pseudo URL prefix for all matching resources from the class path: "classpath*:"
 * This differs from ResourceLoader's classpath URL prefix in that it
 * retrieves all matching resources for a given name (e.g. "/beans.xml"),
 * for example in the root of all deployed JAR files.
 * @see org.springframework.core.io.ResourceLoader#CLASSPATH_URL_PREFIX
 */
String CLASSPATH_ALL_URL_PREFIX = "classpath*:";

由于类路径中没有与名称匹配的 XML 文件application-context-this-does-not-exist.xml,因此您的配置等于@ContextConfiguration(locations={})=> empty application context

但是,当您使用CLASSPATH_URL_PREFIX = "classpath:"时,等于说“加载此不存在的文件” =>错误加载上下文配置

于 2013-06-08T18:20:11.470 回答