Spring Boot: Profiles ignored in PropertySourcesPl

2019-07-20 03:50发布

问题:

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.

回答1:

By default, the PropertySourcesPlaceholderConfigurer knows nothing about only getting profile specific props. If you have a prop defined multiple times in a file such as env, it will bind the value associated with the last occurrence of that prop (in this case prod).

To make it bind props matching a specific profile, set a profile document matcher. The profile document matcher will need to know the active profile which can be obtained from the environment. Here's the code:

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