RunWith and ContextConfiguration weird behaviour

2019-01-24 10:06发布

问题:

I have this very simple class :

 @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");
    }
}

This context file that is specified in classpath DOES NOT EXIST. I can put virtually any name I want and the code does not break. I mean the test runs just fine, as if that file really exists.

If I do a small change, from : classpath* to classpath , then it beaks, saying that this file does not exist, which is the behavior I would expect in the first case also.

Spring Version 3.2.3.RELEASE.

Can someone explain this weird behavior?

EDIT

Things from logs as suggested:

     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

I even tried to output all beans from application context:

  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

Seems to me that in case of a wildcard, Spring will create a default empty Application Context

回答1:

Quote from JavaDoc will probably answer your question:

/**
 * 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*:";

As there are no XML files matching the name application-context-this-does-not-exist.xml on your classpath, your configuration is equal to @ContextConfiguration(locations={}) => empty application context.

However when you use CLASSPATH_URL_PREFIX = "classpath:", that equals to saying "load this non-existing file" => error loading context configuration.