java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > springboot配置多个yml文件

springboot实现配置多个yml文件

作者:码农小C

文章主要介绍了在Spring Boot项目中实现多环境配置的三种方式:方式一、多YAML文件配置;方式二、单YAML文件配置;方式三、在pom.xml中指定环境配置,每种方式都有其特点和适用场景

掌握方式一就够了,方式二、三可以不看

以下三种方式都可以实现多环境的配置。在application.yml主配置文件中做项目通用的配置,在其他配置文件中做不同环境下的配置,以避免重复配置的情况。

方式一:多个yml文件

步骤一、多个配置文件

application.yml      #主配置文件
application-dev.yml  #开发环境的配置
application-prod.yml #生产环境的配置
application-test.yml #测试环境的配置

步骤二、applicaiton.yml中指定配置

在application.yml中选择需要使用的配置文件(当选择的文件和application.yml文件存在相同的配置时,application.yml中的配置会被覆盖掉)

spring:
 profiles:
   active: dev #需要使用的配置文件的后缀

方式二: 单个yml文件

配置默认的profile为dev,其他环境可以通过指定启动参数来使用不同的profile,比如:

#激活dev环境配置
spring:
  profiles.active: dev
 
# 开发环境配置
spring:
  profiles: dev
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/dev?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver
server:
  port: 8080
 
# 测试环境配置
spring:
  profiles: test
  datasource:
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
    username: root
    password: test
    driver-class-name: com.mysql.jdbc.Driver
server:
  port: 88
 
# 生产环境配置
spring:
  profiles: prod
  datasource:
    url: jdbc:mysql://localhost:3306/prod?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
    username: root
    password: prod
    driver-class-name: com.mysql.jdbc.Driver
 server:
  port: 99

方式三:在pom.xml中指定环境配置

步骤一、创建多个配置文件

application.yml      #主配置文件
application-dev.yml  #开发环境的配置
application-prod.yml #生产环境的配置
application-test.yml #测试环境的配置

步骤二、在application.yml中添加多环境配置属性

#多环境配置
  profiles:
    active: @profiles.active@

步骤三、在pom.xml中指定使用的配置

true配置为true则激活对应profile的配置。

或如图所示,在maven->profiles下勾选动态激活需要使用的配置

   <profiles>
        <profile>
            <id>dev</id>
            <activation>
                <!--  默认激活-->
                <activeByDefault>true</activeByDefault>
            </activation>
            <properties>
                <profiles.active>dev</profiles.active>
            </properties>
        </profile>
 
        <profile>
            <id>prod</id>
            <properties>
                <profiles.active>prod</profiles.active>
            </properties>
        </profile>
 
        <profile>
            <id>test</id>
            <properties>
                <profiles.active>test</profiles.active>
            </properties>
        </profile>
    </profiles>

方式三的闭坑:

避坑:不能识别符号@

在方式三的步骤二中配置的@profiles.active@,启动会报异常,不能识别@符号。解决方法:

在pom.xml中设置filtering为true

   <build>
       <resources>
          <resource>
              <directory>src/main/resources</directory>
              <filtering>true</filtering> 
              <includes>
                  <include>**/*.*</include>
              </includes>
          </resource>
      </resources>
</build>

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文