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

标签 java spring-boot

我有一个位于类路径资源中的内部 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, if spring.config.location is configured with the value classpath:/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/

相关文章:

javax.xml.绑定(bind).JAXBException : class <ClassName> nor any of its super class is known to this context

java - 分页Spring启动JPA异常:Method has to have one of the following return types

java - 将 WAR 部署到 Tomcat(Spring Boot + Angular)

java - Spring Boot Thymeleaf 显示不工作

java - 如何知道 Java 应用程序是否使用 MVC 设计模式?

java - 将 R 连接到远程服务器上的 Hive

java - 如何计算和级数 1+1/2...+1/n

java - jmeter 测试计划导航 Pane 字体大小

javascript - 插入对象时未返回响应

java - java中的超时值超过启动取消azure函数