我可以在 Spring 引导中激活 @PropertySource 文件中的配置文件吗?

Can I activate profile in @PropertySource file in Spring Boot?

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

开始

我的申请

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

my.properties:

spring.profiles.active=STAT
abc=ABC

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

No active profile set, falling back to default profiles: default

Display:ABC

也许我应该解释一下我想要实现的目标。我的预 Spring 启动应用程序行为取决于环境,例如,如果使用 $ENV=DEV 开发配置。我想迁移到 Spring 引导并将配置放入配置文件,但我想保持环境不变。 我想实现那个

if $ENV=DEV then profile DEV is selected

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

不,你不能那样做。 @PropertySource 阅读太晚,无法对申请产生任何影响 bootstrap。

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);
}