小编Ale*_*sei的帖子

如何在运行时切换弹簧配置文件

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

@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
    }

}
Run Code Online (Sandbox Code Playgroud)

配置类

@Configuration
@ConfigurationProperties
public class Config{ …
Run Code Online (Sandbox Code Playgroud)

java profile spring spring-boot

1
推荐指数
1
解决办法
7817
查看次数

标签 统计

java ×1

profile ×1

spring ×1

spring-boot ×1