【问题标题】:Spring boot : load profile specific application.properties from file systemSpring boot:从文件系统加载配置文件特定的 application.properties
【发布时间】:2019-02-22 11:47:22
【问题描述】:

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

以及我定义的属性文件如下:

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

【问题讨论】:

  • so所有的配置都有不同的key-> value?如果是,为什么不合并到一个属性文件中,如果他们有相同的key,你应该自己做
  • 你能在'application.properties'中设置'spring.profiles.active=dev, qa, etc',还是在运行jar时设置命令行参数t加载特定属性'java -jar -Dspring .profiles.active=生产演示-0.0.1-SNAPSHOT.jar'
  • 是的,当我使用 -Dspring.profiles.active=qa 选项运行 jar 文件时,我仍然得到在 application.properties 中定义的值,而不是在 application-qa.properties 中定义的值

标签: spring spring-boot properties-file


【解决方案1】:

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

就像这里的代码 sn-p,它会寻找属性 'envTarget',如果它没有找到或为空,它将使用默认的 'qa':

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

【讨论】:

    【解决方案2】:

    首先使用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,因为这不是必需的。

    【讨论】:

    • 这是非常巧妙的解决方案,谢谢
    猜你喜欢
    • 2015-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-21
    • 2020-02-13
    • 2017-01-26
    • 2014-10-11
    • 2019-01-05
    相关资源
    最近更新 更多