springboot怎么读取指定配置文件

avatar
作者
筋斗云
阅读量:0

Spring Boot 默认会读取 application.properties 或 application.yml 配置文件。如果你想读取其他指定的配置文件,可以通过在 application.properties 或 application.yml 文件中配置 spring.config.name 或 spring.config.location 属性来指定。

  1. 在 application.properties 或 application.yml 文件中配置 spring.config.name 属性,值为你想要读取的配置文件的名称(不包含扩展名)。例如,如果你想读取 myconfig.properties 文件,可以在 application.properties 文件中添加以下配置:
spring.config.name=myconfig 
  1. 如果你的配置文件不在默认的 classpath 目录下,你还需要配置 spring.config.location 属性,值为你的配置文件的绝对路径或相对于 classpath 的路径。例如,如果你的配置文件在 /opt/config/myconfig.properties,可以在 application.properties 文件中添加以下配置:
spring.config.name=myconfig spring.config.location=file:/opt/config/ 

或者,如果你的配置文件在 classpath:config/ 目录下,可以在 application.properties 文件中添加以下配置:

spring.config.name=myconfig spring.config.location=classpath:config/ 

注意:如果你同时配置了 spring.config.name 和 spring.config.location 属性,Spring Boot 会先查找 spring.config.location 指定的路径下的文件,如果找不到再去查找 classpath 下的文件。

  1. 使用 @PropertySource 注解读取指定配置文件。在你的配置类上添加 @PropertySource 注解,并指定要读取的配置文件的路径。例如,如果你想读取 myconfig.properties 文件,可以在配置类上添加以下注解:
@Configuration @PropertySource("classpath:myconfig.properties") public class MyConfig {     // ... } 

以上是读取指定配置文件的几种方式,你可以根据你的需求选择合适的方式。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!