Spring Boot: Profiles ignored in PropertySourcesPlaceholderConfigurer loaded file

泪湿孤枕 提交于 2019-12-11 03:52:15

问题


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


来源:https://stackoverflow.com/questions/47717871/spring-boot-profiles-ignored-in-propertysourcesplaceholderconfigurer-loaded-fil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!