【问题标题】:Can I activate profile in @PropertySource file in Spring Boot?我可以在 Spring Boot 的 @PropertySource 文件中激活配置文件吗?
【发布时间】:2017-04-12 11:39:09
【问题描述】:

我想从应用程序中的属性文件中激活配置文件。最终我想动态激活配置文件,但我想从静态开始

我的申请

@SpringBootApplication @PropertySource("classpath:/my.properties")
public class Application {

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

  @Component public static class MyBean {
    @Autowired public void display(@Value("${abc}") String abc) {
        System.out.println("Post:"+ abc);
    }

我的属性:

spring.profiles.active=STAT
abc=ABC

我的输出证明 my.properties 已被读取,但配置文件被忽略

未设置活动配置文件,回退到默认配置文件:默认

显示:ABC

也许我应该解释一下我想要实现的目标。我的 pre-Spring Boot 应用程序行为取决于环境,例如是否使用了 $ENV=DEV 开发配置。我想迁移到 Spring boot 并将配置放入配置文件,但我想保持环境不变。 我想实现它

if $ENV=DEV then profile DEV is selected

我的想法是添加my.properties 和spring.profiles.active=$ENV,但它不起作用

【问题讨论】:

    标签: spring-boot spring-profiles


    【解决方案1】:

    不,你不能那样做。 @PropertySource 被读取太晚,不会对应用程序引导产生任何影响。

    SpringApplication 只是一个更完整的东西的捷径。您可以在那里读取您需要的任何属性并在应用启动之前启用配置文件,例如:

    public static void main(String[] args) {
      String env = System.getenv().get("ENV");
      // Some sanity checks on `env`
      new SpringApplicationBuilder(Application.class).profiles(env).run(args);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-05
      • 1970-01-01
      • 2010-10-30
      • 2016-08-22
      • 2017-02-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多