title: How to set active profile programmatically for any environment?
body: <p>I want to set active profile host dependent for any envrionment and cannot find an environment independent hook.</p>
  
  <p>Following factory will set the active profile before application context will build.</p>
  
  <p><strong>/META-INF/spring.factories</strong></p>
  
  <pre><code>org.springframework.context.ApplicationContextInitializer=MyApplicationContextInitializer
  </code></pre>
  
  <p><strong>MyApplicationContextInitializer.java</strong></p>
  
  <pre><code>public class MyApplicationContextInitializer implements ApplicationContextInitializer&lt;ConfigurableApplicationContext&gt; {
      @Override
      public void initialize(ConfigurableApplicationContext ca) {
          ConfigurableEnvironment environment = ca.getEnvironment();
          environment.addActiveProfile("myHost");
      }
  }
  </code></pre>
  
  <p>If this example is executed in a mock environment by JUnit ...</p>
  
  <p><strong>*Test.java</strong></p>
  
  <pre><code>...
  @RunWith(SpringRunner.class)
  @SpringBootTest
  @AutoConfigureMockMvc
  ...
  </code></pre>
  
  <p>... following will be logged.</p>
  
  <pre><code>...
  ... RestControllerTests   : The following profiles are active: myHost
  ...
  </code></pre>
  
  <p><strong>but profile <em>myHost</em> is not active and default profile will be used in context of JUnit!</strong></p>
  
  <p>A test as Java Application and JUnit with VM arguments works ...</p>
  
  <pre><code>-Dspring.profiles.active=myHost
  </code></pre>
  
  <p>I use a war packaged spring-boot-starter-web app and programmatically profile shall be set and used in any environment </p>
  
  <ul>
  <li>Java Application</li>
  <li>JUnit</li>
  <li>Servlet Container</li>
  </ul>
  
  <p>How do I set the profile <strong>programmatically</strong> for any environmnet?</p>
  
  <p>I do not want to use VM arguments or environemt variables because the profile shall be set by the current host name.</p>