springboot怎么读取指定配置文件

   2025-02-13 3140
核心提示:Spring Boot 默认会读取 application.properties 或 application.yml 配置文件。如果你想读取其他指定的配置文件,可以通过在 ap

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

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

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

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

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

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

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

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言