Spring Boot:在加载PropertySourcesPlaceholderConfigurer文件时忽略配置文件中的Profiles

3

我有一个库,它是一个Spring Boot项目。该库有一个library.yml文件,其中包含其配置的dev和prod属性:

library.yml

---
spring:
    profiles: 
        active: dev
---
spring:
    profiles: dev
env: dev
---
spring:
    profiles: prod
env: prod

另一个应用程序使用此库并使用以下方式加载道具:
@Bean
public static PropertySourcesPlaceholderConfigurer dataProperties() {
  PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
  YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
  yaml.setResources(new ClassPathResource("library.yml"));
  propertySourcesPlaceholderConfigurer.setProperties(yaml.getObject());
  return propertySourcesPlaceholderConfigurer;
}

其application.yml文件指定使用开发环境属性:
---
spring:
    profiles: 
        active: dev

但是当我检查env的值时,我得到的是"prod"。为什么?
如何告诉Spring Boot在library.yml中使用活动(例如dev)配置文件属性?
注意:我更喜欢使用.yml文件而不是.properties文件。

你尝试过将 --spring.profiles.active=dev 作为命令行参数传递吗? - Aruna Karunarathna
不过,我已经验证了活动配置文件为dev。我有一个解决方案,我将发布。 - James
1个回答

3
默认情况下,PropertySourcesPlaceholderConfigurer 不知道只获取特定配置文件的属性。如果在一个文件中定义了多个属性,例如 env,它将绑定与该属性的最后一次出现相关联的值(在这种情况下为 prod)。
要使其绑定与特定配置文件匹配的属性,请设置配置文件匹配器。配置文件匹配器需要知道活动配置文件,可以从环境中获取。以下是代码:
@Bean
public static PropertySourcesPlaceholderConfigurer dataProperties(Environment environment) {
  PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
  YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
  SpringProfileDocumentMatcher matcher = new SpringProfileDocumentMatcher();
  matcher.addActiveProfiles(environment.getActiveProfiles());
  yaml.setDocumentMatchers(matcher);
  yaml.setResources(new ClassPathResource("library.yml"));
  propertySourcesPlaceholderConfigurer.setProperties(yaml.getObject());
  return propertySourcesPlaceholderConfigurer;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接