title: Spring - Switch between loading test or main configuration
body: <p>I am trying to swap application-context files so I can test in my IDE using the real one or test in my IDE using JUnit with a test one. </p>
  
  <p>A bare bones example would be:</p>
  
  <p>mainConfig.xml</p>
  
  <pre><code>&lt;context:component-scan base-package="myPackage" /&gt;
  &lt;bean id="myBean" class="my.class"/&gt;
  </code></pre>
  
  <p>testConfig.xml</p>
  
  <pre><code>&lt;context:component-scan base-package="myPackage" /&gt;
  &lt;bean id="myBean" class="my.test.class"/&gt;
  </code></pre>
  
  <p>My java code that deals with the application Context is similar to below (but is really a singleton)</p>
  
  <pre><code>public final class MyLoader {
  
      private ApplicationContext context;
  
      public MyLoader(){
          context = new ClassPathXmlApplicationContext(
              "classpath:/hardcoded/path/to/mainConfig.xml");
      }
  
      public &lt;T&gt; T getComponent(final Class&lt;T&gt; type) {
          return (T) context.getBean(type);
      }
  }
  </code></pre>
  
  <p>MyLoader is called from multiple points in the code since there are many different entry points into the application.</p>
  
  <p>My JUnit test code</p>
  
  <pre><code>@RunWith(SpringJUnit4ClassRunner.class)
  @ContextConfiguration("classpath:/hardcoded/path/to/testConfig.xml")
  public final class Foo{}
  </code></pre>
  
  <p>When I run a JUnit test, it will load the testConfig.xml (due to the @ContextConfiguration in the JUnit file), but it will also load the mainConfig.xml (because of the ClassPathXmlApplication). This will cause a clash since the two files are different.</p>
  
  <p>What is the correct way to have all this wired where mismatches like this will not occur?</p>