title: How to switch spring profile at runtime
body: <p>I have spring boot application with profiles. Now I want to switch profile at runtime, refresh spring context and continue application execution. How to switch active profile at runtime (switchEnvironment method)?</p>
  
  <pre><code>@SpringBootApplication
  public class Application implements CommandLineRunner {
  
      @Autowired
      private Config config;
  
      public static void main(String[] args) {
          SpringApplication.run(Application.class, args);
      }
  
      @Override
      public void run(String ... strings) throws Exception {
          System.out.printf("Application is running in %s environment, service parameters below:\n",
                  getEnvProperty("spring.profiles.active").toUpperCase());
          printServiceParameters();
          switchEnvironment();
          printServiceParameters();
      }
  
      private String getEnvProperty(String propertyName) {
          return config.getEnv().getProperty(propertyName);
      }
  
      private void printServiceParameters() {
          System.out.println(getEnvProperty("service.endpoint"));
      }
  
      private void switchEnvironment() {
          //todo Switch active profile
      }
  
  }
  </code></pre>
  
  <p>Config.class</p>
  
  <pre><code>@Configuration
  @ConfigurationProperties
  public class Config{
  
      @Autowired
      private ConfigurableEnvironment env;
  
      public ConfigurableEnvironment getEnv() {
          return env;
      }
  
      public void setEnv(ConfigurableEnvironment env) {
          this.env = env;
      }
  
  }
  </code></pre>