关于SpringBoot打包测试、生产环境方式
作者:lee84233
这篇文章主要介绍了关于SpringBoot打包测试、生产环境方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
1. SpringBoot创建不同环境的配置文件
1.1 新建各环境的配置文件
resources 目录下新建 application-dev.yml 、 application-test.yml 、 application-prod.yml 文件
分别对应 开发、测试、生产环境

1.2 修改 application.yml
application.yml 修改配置参数
spring:
profiles:
active: @profiles.active@2. 修改 pom.xml
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<!--fork: 如果没有该项配置,整个 devtools 不会起作用-->
<fork>true</fork>
<!--启动类-->
<mainClass>com.xx.DemoApplication</mainClass>
</configuration>
<executions>
<execution>
<goals>
<!--创建一个自动可执行的jar或war文件 -->
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<!-- 资源根目录排除各环境的配置,防止在生成目录中多余其它目录 -->
<filtering>true</filtering>
<excludes>
<exclude>application*.yml</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>application.yml</include>
<include>application-${profiles.active}.yml</include>
</includes>
</resource>
</resources>
</build>
<!-- 不同环境的配置 -->
<profiles>
<!--开发环境-->
<profile>
<id>dev</id>
<properties>
<profiles.active>dev</profiles.active>
</properties>
<!--默认激活-->
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<!--测试环境-->
<profile>
<id>test</id>
<properties>
<profiles.active>test</profiles.active>
</properties>
</profile>
<!--生产环境-->
<profile>
<id>prod</id>
<properties>
<profiles.active>prod</profiles.active>
</properties>
</profile>
</profiles>3. 打成指定环境的 jar包
3.1 使用 idea 开发工具进行打包
使用 idea 开发工具操作即可,方便快捷:
- 打开右侧的
Maven工具栏。 - 双击
clean,先清理一下。 - 勾选需要打包的环境
- 双击
package,等到 SUCCESS后,查看target目录下,会有打包的项目jar包。
操作步骤如图:

3.2 命令行打包
执行命令:
mvn clean package -P {环境名} -D maven.test.skip=true示例(打包test环境):
mvn clean package -P test -D maven.test.skip=true
3.3 成功后的jar包
查看 target 目录下的 jar 包

4. 本地运行jar包
jar包所在的路径下,执行:
java -jar -D spring.profiles.active={环境名} {jar包名}示例
(打包的test环境,打包后jar包名为 springboot-demo1-1.0.0-SNAPSHOT.jar):
java -jar -D spring.profiles.active=test springboot-demo1-1.0.0-SNAPSHOT.jar
示例图:


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