3

I have a library that is a Spring Boot project. The library has a library.yml file that contains dev and prod props for its configuration:

library.yml

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

Another application uses this library and loads the props using:

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

And its application.yml says to use dev props:

---
spring:
    profiles: 
        active: dev

But when I check the value of env, I get "prod". Why?

How can I tell Spring Boot to use the active (e.g. dev) profile props in library.yml?

Note: I prefer to use .yml instead .properties files.

4

1 回答 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;
}
于 2017-12-08T17:08:51.947 回答