如何在运行时切换弹簧轮廓

时间:2018-02-01 19:26:34

标签: java spring spring-boot profile

我有配置文件的春季启动应用程序。现在我想在运行时切换配置文件,刷新spring上下文并继续执行应用程序。如何在运行时切换活动配置文件(switchEnvironment方法)?

@Configuration
@ConfigurationProperties
public class Config{

    @Autowired
    private ConfigurableEnvironment env;

    public ConfigurableEnvironment getEnv() {
        return env;
    }

    public void setEnv(ConfigurableEnvironment env) {
        this.env = env;
    }

}

Config.class

<?php 

    if (!empty($_POST)) {
      header("access-control-allow-credentials:true");
      header("access-control-allow-headers:Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token");
      header("access-control-allow-methods:POST, GET, OPTIONS");
      header("access-control-allow-origin:".$_SERVER['HTTP_ORIGIN']);
      header("access-control-expose-headers:AMP-Access-Control-Allow-Source-Origin");
      // change to represent your site's protocol, either http or https
      header("amp-access-control-allow-source-origin:https://".$_SERVER['HTTP_HOST']);
      header("Content-Type: application/json");
      $firstName = isset($_POST['first_name']) ? $_POST['first_name'] : '';
      $lastName = isset($_POST['last_name']) ? $_POST['last_name'] : '';
      $phone = isset($_POST['your_phone_number']) ? $_POST['your_phone_number'] : '';
      $email = isset($_POST['your_email']) ? $_POST['your_email'] : '';
      $city = isset($_POST['driver_app_request_call_hiring_city']) ? $_POST['driver_app_request_call_hiring_city'] : '';

      try {
        include "JotForm.php";
        $jotformAPI = new JotForm("APIkey");
        $submission = array(
            "3" => $firstName,
            "4" => $lastName,
            "5" => $phone,
            "6" => $email,
            "7" => $city
        );
        $result = $jotformAPI->createFormSubmission("formId", $submission);
        $output = ['message' => "Your application was submitted. Thank you!"];
        header("Content-Type: application/json");
        echo json_encode($output);

      } catch (Exception $e) {
        var_dump($e->getMessage());
      }
  }
?>

2 个答案:

答案 0 :(得分:3)

所有您需要的东西,都会将此方法添加到您的主类中,并创建Controller或Service来调用此方法。

@SpringBootApplication
public class Application {

    private static ConfigurableApplicationContext context;

    public static void main(String[] args) {
        context = SpringApplication.run(Application.class, args);
    }

    public static void restart() {

        Thread thread = new Thread(() -> {
            context.close();
            context = SpringApplication.run(Application.class, "--spring.profiles.active=your_profile");
        });

        thread.setDaemon(false);
        thread.start();
    }

}

控制器:

@RestController
public class RestartController {

    @PostMapping("/restart")
    public void restart() {
        Application.restart();
    }
}

答案 1 :(得分:0)

要详细说明其他一些答案,这就是Netflix Archaius(https://github.com/Netflix/archaius/wiki)尝试解决的工具(动态上下文配置)。据我所知,实现此目的的唯一方法是通过重新启动应用程序来刷新上下文。