title: How to set Spring Active Profiles Pragmatically from a configuration class?
body: <p>On a project I'm working on we have some old dependencies that define their own spring beans but need to be initialized from the main application. These beans are all constructed using spring profiles, i.e. "default" for production code and "test" for test code. We want to move away from using spring profiles, instead simply using @import to explicitly wire up our context. </p>
  
  <p>The idea is to encapsulate all these old dependencies so that no other components need to care about spring profiles. Thus, from a test`s point of view, the application context setup can be described as follows:</p>
  
  <pre><code>@ContextConfiguration(classes = {TestContext.class})
  @RunWith(SpringJUnit4ClassRunner.class)
  public class MyTest { 
    //tests
  }
  </code></pre>
  
  <p>TestContext further directs to two classes, one of which encapsulates the old dependencies:</p>
  
  <pre><code>@Configuration
  @Import(value = {OldComponents.class, NewComponents.class})
  public class TestContext {
    //common spring context
  }
  </code></pre>
  
  <p>To encapsulate the old components` need for profiles, the OldComponents.class looks as follows:</p>
  
  <pre><code>@Configuration
  @Import(value = {OldContext1.class, OldContext2.class})
  public class OldComponents {
  
    static {
      System.setProperty("spring.profiles.active", "test");
    }
  
  }
  </code></pre>
  
  <p>The problem here is that the static block does not appear to be executed in time. When running mvn clean install, the test gets an IllegalStateException because the ApplicationContext could not be loaded. I have verified that the static block gets executed, but it would appear that OldContext1 and OldContext2 (which are profile dependent) are already loaded at this time, which means it is too late. </p>
  
  <p>The frustrating thing is that IntelliJ runs the tests just fine this way. Maven, however, does not. Is there a way to force these profiles while keeping it encapsulated? I've tried creating an intermediary context class, but it didn't solve the problem. </p>
  
  <p>If we use the annotation @ActiveProfiles on the test class, it runs just fine but this kind of defeats the purpose. Naturally, we want to achieve the same in production and this means that if we cannot encapsulate the need for profiles, it needs to be configured in the web.xml. </p>