繁体   English   中英

Spring没有正确地从外部配置文件加载属性

[英]Spring not loading properties from external config file properly

我有一个内部application.yml文件位于classpath资源中,包含以下字段:

redis:
  hostname: localhost
  port: 6379
  database: 0
  password:

有一个外部配置文件: config.properties 它定义了一些要在我的服务器上下文中重写的字段。 文件config.properties

redis.hostname = db.example.com
redis.password = my_password

应用程序无法启动,因为它无法读取配置文件中的redis.port属性。 我怀疑的是,如果已经发现外部文件中定义了一些字段(在这种情况下是主机名,密码),则spring不会完全保留属性源( redis )的字段。

我正在使用以下命令运行应用程序:

java -jar -Dspring.config.location=file:///home/username/config.properties application.jar

如何使spring正确覆盖内部配置文件,以便它只覆盖额外的属性(redis.hostname,redis.password),但仍保留内部文件中定义的其他字段(如redis.port,redis.database)但没有在外部文件中定义?

PS:我知道这就是发生的事情,因为当我在外部配置文件中添加redis.port = 6379属性时,应用程序正常工作。

第1步:阅读Spring Boot文档

以相反的顺序搜索配置位置。 默认情况下,配置的位置是classpath:/,classpath:/config/,file:./,file:./config/ 生成的搜索顺序如下:

 file:./config/ file:./ classpath:/config/ classpath:/ 

使用spring.config.location配置自定义配置位置时,它们将替换默认位置 例如,如果spring.config.location配置了值classpath:/custom-config/,file:./custom-config/ spring.config.location classpath:/custom-config/,file:./custom-config/ ,搜索顺序将变为以下内容:

 file:./custom-config/ classpath:custom-config/ 

第2步:指定正确的值:

-Dspring.config.location=classpath:/,file:///home/username/config.properties
file:

classpath:

在代码中绑定配置时需要指定。 指定-D参数时,可以相对于jar文件位置传递属性文件的地址。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM