我正在尝试根据当前活动配置文件加载外部属性文件
以及我定义如下的属性文件:
default -> resources/config/application.properties (for dev)
qa -> c:external-configurationconfigapplication-qa.properties
prod -> c:external-configurationconfigapplication-prod.properties
如何配置 Spring 以从不同来源读取所有这些application*.properties
?
我尝试定义如下PropertySourcesPlaceholderConfigurer
,但 spring 可以根据活动配置文件解析属性值,我总是得到application.properties
中定义的默认值
@Bean
public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
PropertySourcesPlaceholderConfigurer properties = new PropertySourcesPlaceholderConfigurer();
properties.setLocation(new FileSystemResource("c:external-configurationconfigapplication-qa.properties"),new FileSystemResource("c:external-configurationconfigapplication-prod.properties"));
properties.setIgnoreResourceNotFound(false);
return properties;
}
首先指定要使用spring.profiles.active
加载的配置文件。其次,由于它不是默认位置之一,因此添加spring.config.additional-location
以添加要扫描的其他位置。所以当你开始你的行应该看起来像
java -jar <your-jar>.jar --spring.profiles.active=prod --spring.config.additional-location=file:C:/external-configuration/config/
这也记录在 Spring 引导文档中。
并删除您的自定义PropertySourcesPlaceholderConfigurer
,因为不需要。
还可以对属性资源使用 java 注释,并使用服务器环境(活动配置文件(来标识要加载的属性文件。
就像这里的代码片段一样,它将查找属性"envTarget",如果未找到或为 null,它将使用默认的"qa":
@PropertySource({
"classpath:application-${envTarget:qa}.properties"
})