我有一个位于类路径资源中的内部 application.yml 文件,其中包含以下字段:
redis:
hostname: localhost
port: 6379
database: 0
password:
有一个外部配置文件:config.properties。它定义了一些要在我的服务器上下文中覆盖的字段。文件config.properties:
redis.hostname = db.example.com
redis.password = my_password
应用程序无法启动,因为它无法读取配置文件中的 redis.port 属性。我的疑问是,如果 spring 已经找到在外部文件中定义的一些字段(在本例中为主机名、密码),那么 spring 不会完全保留属性源(redis)的字段。
我正在使用以下命令运行应用程序:
java -jar -Dspring.config.location=file:///home/username/config.properties application.jar
如何让 spring 正确地覆盖内部配置文件,以便它只覆盖额外的属性(redis.hostname、redis.password),但仍保留内部文件中定义的其他字段(如 redis.port、redis.数据库)但未在外部文件中定义?
P.S:我知道这是怎么回事,因为当我在外部配置文件中添加 redis.port=6379 属性时,应用程序可以正常工作。
最佳答案
第 1 步:阅读 Spring Boot documentation :
Config locations are searched in reverse order. By default, the configured locations are
classpath:/,classpath:/config/,file:./,file:./config/
. The resulting search order is the following:file:./config/ file:./ classpath:/config/ classpath:/
When custom config locations are configured by using
spring.config.location
, they replace the default locations. For example, ifspring.config.location
is configured with the valueclasspath:/custom-config/,file:./custom-config/
, the search order becomes the following:file:./custom-config/ classpath:custom-config/
第 2 步:指定正确的值:
-Dspring.config.location=classpath:/,file:///home/username/config.properties
关于java - Spring 没有正确地从外部配置文件加载属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54174333/