温馨提示×

springboot怎么读取指定配置文件

小亿
95
2023-12-01 15:27:27
栏目: 编程语言

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 {
    // ...
}

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

0