作用

  1. 开发、公布过程中,须要切换多种环境(如数据库链接,端口号等)
  2. 网上搜寻了,后果搜到很多辣鸡文章,漏了要害信息配不胜利,所以写下亲测可用的过程,防止前面的老铁被耽搁
  3. 最初终于找到了一篇正确的,不过内容不简练,重新整理取得,大家也能够间接看原文章:
https://blog.csdn.net/xiaocho...

次要步骤

  1. 在pom.xml增加配置
  2. 在resources增加对应环境的配置文件
  3. 运行指定配置

环境

idea2020
spring-boot 2.3.1RELEASE
JDK 14.0.2

具体步骤

1.在pom.xml中增加配置

增加环境

<profiles>    <profile>        <id>dev</id>        <properties>            <environment>dev</environment>  <!-- 环境名,能够任意名字,在资源配置中应用 ${environment}就能获取值 -->        </properties>        <activation>            <activeByDefault>true</activeByDefault>  <!-- 默认环境,当应用mvn启动不指定配置时,默认应用这个环境 -->        </activation>    </profile>    <profile>        <id>beta</id>        <properties>            <environment>beta</environment>  <!-- beta环境 -->        </properties>    </profile></profiles>

增加资源配置

<build>    <resources>        <resource>            <directory>src/main/resources</directory>            <includes>                <include>application.properties  </include><!-- 原配置文件 -->                <include>application-${environment}.properties</include>  <!-- 带环境的配置文件,留神应用"-"连贯,否则无奈失效 -->                <include>**/*.xml</include>  <!-- 其余资源文件,不填写会导致程序运行时找不到文件 -->                <include>**/*.sql</include>  <!-- 其余资源文件,不填写会导致程序运行时找不到文件 -->            </includes>            <filtering>true</filtering>  <!-- 过滤,不晓得啥成果,有趣味的能够本人批改测试下 -->        </resource>    </resources></build>

此时在Maven窗口会看到配置选项

增加配置文件

增加application-dev.properties
增加application-beta.properties
两个文件名对应pom.xml中的 application-${environment}.properties

环境配置文件是在原配置上叠加笼罩的

# 如application.properties中server.port=8080# 如application-dev.properties中server.port=8081spring.datasource.username=dev# 如application-beta.properties中server.port=8082spring.datasource.username=beta

后果dev环境中:port=8081,username=dev
beta环境中:port=8082,username=beta

应用配置

启动的命令后加上 -P 配置名称

mvnw clean spring-boot:run          # 应用默认配置(此例子中是dev)mvnw clean spring-boot:run -P beta  # 应用beta环境mvnw clean spring-boot:run -P dev   # 应用dev环境mvnw clean package                  # 应用默认配置(此例子中是dev)mvnw clean package -P beta          # 应用beta环境mvnw clean package -P dev           # 应用dev环境

查看后果

很显著能够察看到,指定不同环境启动时,端口号是对应的配置文件上的