zl程序教程

您现在的位置是:首页 >  后端

当前栏目

springboot的外部化配置及配置文件加载顺序

SpringBoot配置配置文件 加载 顺序 外部
2023-09-11 14:16:24 时间

默认配置文件位置

springboot 启动会扫描以下位置的application.properties或者application.yml文件作为Spring boot的默认配置文件,
加载顺序及优先级如下:

  • file:./config/
  • file:./
  • classpath:/config/
  • classpath:/

优先级由高到底,高优先级的配置会覆盖低优先级的配置;
SpringBoot会从这些位置全部加载主配置文件;互补配置;

自定义配置文件位置

通过spring.config.location增加自定义的配置文件存放目录,比如:
classpath:/custom-config/ 或者 file:./custom-config/

则加载顺序变为:

  • file:./custom-config/
  • classpath:custom-config/
  • file:./config/
  • file:./
  • classpath:/config/
  • classpath:/

追加配置文件

–spring.config.additional-location=“D:/xxx/conf/”
顾名思义,该命令用于追加配置文件。原有的application.properties或application.yml文件均有效。

自定义配置文件名称

通过spring.config.name 修改默认的配置文件名称
java -jar myproject.jar --spring.config.name=myproject

激活指定的配置文件

–spring.profiles.active=prod
则激活的配置文件优先级最高

springboot的外部化配置

Spring Boot允许您外部化配置,这样您就可以在不同的环境中使用相同的应用程序代码。您可以使用属性文件、YAML文件、环境变量和命令行参数外部化配置。属性值可以通过使用@Value注释直接注入到bean中,通过Spring的Environment抽象访问,或者通过@ConfigurationProperties绑定到结构化对象
在这里插入图片描述
最新版本2.5.4中,顺序如下:
https://docs.spring.io/spring-boot/docs/2.5.4/reference/htmlsingle/#features.external-config
https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.external-config
在这里插入图片描述