Spring Boot:从文件系统加载特定于配置文件的application.properties

时间:2018-09-18 12:27:14

标签: spring spring-boot properties-file

我正在尝试根据当前的活动配置文件加载外部属性文件

和我定义的属性文件如下:

default -> resources/config/application.properties (for dev)
qa -> c:\external-configuration\config\application-qa.properties
prod -> c:\external-configuration\config\application-prod.properties

如何配置spring以便从不同来源读取所有这些application*.properties

我尝试如下定义PropertySourcesPlaceholderConfigurer,但是spring可以根据活动配置文件解析属性值,我总是得到application.properties中定义的默认值

@Bean
public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
    PropertySourcesPlaceholderConfigurer properties = new PropertySourcesPlaceholderConfigurer();
    properties.setLocation(new FileSystemResource("c:\external-configuration\config\application-qa.properties"),new FileSystemResource("c:\external-configuration\config\application-prod.properties"));
    properties.setIgnoreResourceNotFound(false);
    return properties;
}

2 个答案:

答案 0 :(得分:1)

首先指定要使用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 Boot documentation中。

并删除不需要的自定义PropertySourcesPlaceholderConfigurer

答案 1 :(得分:0)

您还可以将Java注释用于属性资源,并使用服务器环境(活动配置文件)来标识要加载的属性文件。

类似于此代码段,它将查找属性“ envTarget”,如果找不到或为null,它将使用默认的“ qa”:

@PropertySource({ 
  "classpath:application-${envTarget:qa}.properties"
})