我有一个位于类路径资源中的内部application.yml文件,其中包含以下字段:
redis:
hostname: localhost
port: 6379
database: 0
password:
Run Code Online (Sandbox Code Playgroud)
有一个外部配置文件:config.properties。它定义了一些要在我的服务器上下文中覆盖的字段。文件config.properties:
redis.hostname = db.example.com
redis.password = my_password
Run Code Online (Sandbox Code Playgroud)
应用程序无法启动,因为它无法读取配置文件中的 redis.port 属性。我的疑问是,如果 spring 已经找到了外部文件中定义的某些字段(在本例中为主机名、密码),则spring 不会完全保留属性源(redis )的字段。
我正在使用以下命令运行该应用程序:
java -jar -Dspring.config.location=file:///home/username/config.properties application.jar
Run Code Online (Sandbox Code Playgroud)
如何让spring正确覆盖内部配置文件,以便它只覆盖额外的属性(redis.hostname,redis.password),但仍然保留内部文件中定义的其他字段(如redis.port,redis.database)但是没有在外部文件中定义?
PS:我知道正在发生这种情况,因为当我在外部配置文件中添加redis.port=6379属性时,应用程序可以正常工作。
步骤1:阅读Spring Boot文档:
以相反的顺序搜索配置位置。默认情况下,配置的位置是
classpath:/,classpath:/config/,file:./,file:./config/。结果搜索顺序如下:Run Code Online (Sandbox Code Playgroud)file:./config/ file:./ classpath:/config/ classpath:/当使用配置自定义配置位置时
spring.config.location,它们会替换默认位置。例如,如果spring.config.location配置了 valueclasspath:/custom-config/,file:./custom-config/,则搜索顺序变为以下:Run Code Online (Sandbox Code Playgroud)file:./custom-config/ classpath:custom-config/
步骤 2:指定正确的值:
file:./config/
file:./
classpath:/config/
classpath:/
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3146 次 |
| 最近记录: |