Spring引导:在PropertySourcesPlaceholderConfigurer加载的文件中忽略配置文件

Spring引导:在PropertySourcesPlaceholderConfigurer加载的文件中忽略配置文件,spring,spring-boot,spring-profiles,spring-properties,spring-config,Spring,Spring Boot,Spring Profiles,Spring Properties,Spring Config,我有一个库,它是一个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 P

我有一个库,它是一个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表示要使用dev props:

---
spring:
    profiles: 
        active: dev
但是当我检查env的值时,我得到了“prod”。为什么?

如何告诉Spring Boot使用library.yml中的活动(例如dev)配置文件道具


注意:我更喜欢使用.yml而不是.properties文件。

默认情况下,
propertysourcesplaceconfigurer
只知道获取特定于配置文件的道具。如果在文件(如
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;
}

您尝试过将--spring.profiles.active=dev作为命令行参数传递吗?没有。但是我已经验证了活动概要文件是dev。我有一个解决方案要发布。