【问题标题】:Spring Boot Reading Properties Files Based on classpath argSpring Boot 基于类路径 arg 读取属性文件
【发布时间】:2018-02-09 21:07:06
【问题描述】:

我创建了一个独立的 boot.jar,我需要开始将其集成到我们的更高环境中。 每个环境都有一个包含数据库特定连接信息的属性文件。由于这不在我的引导 jar 中,我想以某种方式添加此 database.properties 文件的路径,然后根据键读取条目。用来创建一个像这样的bean:

<bean id="propertyLoader" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
        <value>classpath:application.properties</value>
</property>

但是在启动时,我不确定如何执行此操作:但我想指向下面的属性示例并提取我的值并以某种方式填充我在 dev 中硬编码的 application.properties 值。

server:/config/database.properties
jdbc.username=TEST
jdbc.password=CHANGEME

更新我的 application.properites:

spring.datasource.username='jdbc.username'
spring.datasource.password='jdbc.password'

类似的东西我可以参数化我的 application.properties 文件。

【问题讨论】:

    标签: spring spring-boot


    【解决方案1】:

    SpringBoot 提供配置文件,基本上允许您为每个环境拥有单独的 application.properties 文件。

    你可以有这样的东西:

    public interface DataSourceConfig {}
    
    @Component
    @Profile("dev")
    public DevDataSourceConfig implements DataSourceConfig{}
    
    @Component
    @Profile("prod")
    public ProdDataSourceConfig implements DataSourceConfig{}
    

    如果您将 spring 配置文件 "dev" 设置为活动状态,则只有 DevDataSourceConfig bean 将被实例化,并且在 Spring Environment 中,将被注入的属性将从 application-dev.properties 文件中读取。

    同样,当您激活"prod" 配置文件时,只会实例化ProdDataSourceConfig,并且将从application-prod.properties 文件加载属性。

    这让你拥有:

    ---
    application-dev.properties
    spring.datasource.username='jdbc.username'
    spring.datasource.password='jdbc.password'
    ---
    application-prod.properties
    spring.datasource.username='PROD_jdbc.username'
    spring.datasource.password='PROD_jdbc.password'
    

    如果您想从文件系统上的自定义位置加载配置 - 您可以检查如何使用命令行参数传递位置 (docs)

    例子:

    java -jar boot.jar --spring.config.location=classpath:/database.properties
    

    【讨论】:

      【解决方案2】:

      你已经告诉过你的 jar 中不能有属性文件,仍然有多个选项。

      1> 为各个环境传递一个属性文件。

      java -jar myproject.jar --spring.config.location=classpath:/database.properties 
      

      2> 在调用 jar 时传递属性

      java -jar app.jar --spring.datasource.username="jdbc.username" --spring.datasource.password="jdbc.password"
      

      Read a lot of other options here `

      我会选择选项 1,因为在争论中永远不建议传递凭据。

      【讨论】:

        猜你喜欢
        • 2018-10-12
        • 2020-01-28
        • 1970-01-01
        • 2020-06-05
        • 2016-04-29
        • 2019-03-04
        • 2014-05-01
        • 1970-01-01
        • 2018-10-16
        相关资源
        最近更新 更多