Spring Boot:在PropertySourcesPlaceholderConfigurer加载的文件中忽略了配置文件
我有一个作为Spring Boot项目的库.该库有一个library.yml文件,其中包含用于其配置的dev和prod道具:
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;
}
其application.yml表示要使用开发道具:
And its application.yml says to use dev props:
---
spring:
profiles:
active: dev
但是当我检查env的值时,我得到"prod".为什么?
But when I check the value of env, I get "prod". Why?
如何告诉Spring Boot在library.yml中使用活动的(例如dev)配置文件道具?
How can I tell Spring Boot to use the active (e.g. dev) profile props in library.yml?
注意:我更喜欢使用.yml而不是.properties文件.
Note: I prefer to use .yml instead .properties files.
默认情况下,PropertySourcesPlaceholderConfigurer
对于仅获取个人档案专用道具一无所知.如果在文件(例如env
)中多次定义了prop,它将绑定与该prop的最后一次出现相关的值(在本例中为prod
).
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;
}