java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot多环境配置Maven profile

SpringBoot多环境配置怎么做?Maven profile结合实战教程

作者:做一件事就好

还在为SpringBoot项目在不同环境间切换配置而烦恼吗?本文手把手教你如何利用application-xxx.properties和Maven profile轻松实现多环境配置,动态指定开发、测试、生产环境,包教包会

SpringBoot多环境配置

1、多环境配置

多环境实现是通过多套配置文件实现的,SpringBoot项目中多环境就是通过多个properties配置文件实现:

SpringBoot通过application-xxx来支持多套环境配置,其中application.properties文件中保存公共的配置项,各个环境的配置项放在各自的配置文件中,如图所示

2、环境指定

方式一:直接在application.properties指定环境文件:spring.profiles.active=dev

方式二:配置环境变量,在打包或者启动项目时指定使用的环境名称

Maven的profile实现多套环境

1、多环境配置

在pom中使用profile来指定定义出不同的环境:

  <profiles>
    <profile>
      <id>dev</id>
      <properties>
        <db.driver>com.mysql.jdbc.Driver</db.driver>
        <db.url>jdbc:mysql://localhost:3306/test</db.url>
        <db.username>admin</db.username>
        <db.password>admin</db.password>
      </properties>
      <activation>
        <activeByDefault>true</activeByDefault>
      </activation>
    </profile>
    <profile>
      <id>pre</id>
      <properties>
        <db.driver>com.mysql.jdbc.Driver</db.driver>
        <db.url>jdbc:mysql://localhost:3306/test_db</db.url>
        <db.username>root</db.username>
        <db.password>root</db.password>
      </properties>
    </profile>
    <profile>
      <id>pro</id>
      <properties>
        <db.driver>com.mysql.jdbc.Driver</db.driver>
        <db.url>jdbc:mysql://localhost:3306/test_db</db.url>
        <db.username>root</db.username>
        <db.password>root</db.password>
      </properties>
    </profile>
  </profiles>

2、多环境指定

方式一:使用默认配置

      <activation>
        <activeByDefault>true</activeByDefault>
      </activation>

方式二:使用profiles指定环境

方式三:使用命令指定环境

打包命令:

mvn clean package -P pro

SpringBoot结合Maven的profile实现多环境

1、多环境配置

多环境配置使用SpringBoot的application-xxx.properties实现环境配置;

2、使用profile标识配置环境

3、引用对应的环境

在application.properties中引用对饮的配置文件,通过引用自定义标签来实现

4、使用指定环境变量

参数-P指定的时profile的id,这时候环境变量使用的就是env对应的变量,properties里引用了env,所以就使用了env所标识的变量。

方式一:通过命令来指定对应环境变量:同Maven指定profile命令

mvn clean package -P env_pro

方式二:使用profiles来指定环境:同Maven指定profile命令

总结

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

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