Skip to content

SpringBoot2.4版本后多环境配置文件方案

前言

springboot2.4版本之后,官方针对配置文件进行了改动,更加灵活。

方式

配置文件关系为:

application.yml --> application-(slave).yml

1. application.yml

application.yml 不进行任何配置,只设置spring.profiles.active 属性

2. application-${env}.yml

application-${env}.yml 是不同环境的主配置文件,用于存放一些公共信息。例如 端口,spring.applicatin.name 等

使用属性 spring.config.import 引入指定路径下的配置文件,例如:

yaml
spring:  
  config:
    import:
      - classpath:dev/application-app.yml
      - classpath:dev/application-capi.yml
      - classpath:dev/application-cmc.yml
      - classpath:dev/application-dbrw.yml
      - classpath:dev/application-mybatisplus.yml
      - classpath:dev/application-page.yml
      - classpath:dev/application-redis.yml
      - classpath:dev/application-s3.yml
      - classpath:dev/application-smartbanner.yml
      - classpath:dev/application-smartpopup.yml

3. application-$(slave).yml

application-{env}.yml 的子配置。为了方便维护与查看,我们通常会把此类配置文件放入对应文件夹中。

例如:

dev 文件夹下的 application-redis.yml、application-mysql.yml、applicatin-rabbitmq.yml等

prod 文件夹下的 application-redis.yml、application-mysql.yml、applicatin-rabbitmq.yml等

文件结构

结构如下

shell

+--- application-dev.yml
+--- application-local.yml
+--- application-prod.yml
+--- application.yml
+--- dev
|   +--- application-app.yml
|   +--- application-c3p0.yml
|   +--- application-capi.yml
|   +--- application-cmc.yml
|   +--- application-dbrw.yml
|   +--- application-mybatisplus.yml
|   +--- application-page.yml
|   +--- application-redis.yml
|   +--- application-s3.yml
|   +--- application-smartbanner.yml
|   +--- application-smartpopup.yml
|   +--- application-thymeleaf.yml
|   +--- logback-spring.xml
+--- local
|   +--- application-app.yml
|   +--- application-c3p0.yml
|   +--- application-capi.yml
|   +--- application-cmc.yml
|   +--- application-dbrw.yml
|   +--- application-mybatisplus.yml
|   +--- application-page.yml
|   +--- application-redis.yml
|   +--- application-s3.yml
|   +--- application-smartbanner.yml
|   +--- application-smartpopup.yml
|   +--- application-thymeleaf.yml
|   +--- logback-spring.xml
+--- prod
|   +--- application-app.yml
|   +--- application-c3p0.yml
|   +--- application-capi.yml
|   +--- application-cmc.yml
|   +--- application-dbrw.yml
|   +--- application-mybatisplus.yml
|   +--- application-page.yml
|   +--- application-redis.yml
|   +--- application-s3.yml
|   +--- application-smartbanner.yml
|   +--- application-smartpopup.yml
|   +--- application-thymeleaf.yml
|   +--- logback-spring.xml