SpringBoot maven多环境打包应用

前言

springboot项目可以在运行时指定配置文件,类似这样java -jar xxx.jar --spring.profiles.active=test,test即指的是使用application-test.properties配置文件

在这里插入图片描述
而本文主要介绍

如何在maven打包时指定环境配置文件

修改pom.xml文件

	<profiles>
		<!-- 开发环境 -->
		<profile>
			<id>dev</id>
			<properties>
				<spring.profiles.active>dev</spring.profiles.active>
			</properties>
			<activation>
				<!-- 默认使用dev -->
				<activeByDefault>true</activeByDefault>
			</activation>
		</profile>
		<!-- 测试环境 -->
		<profile>
			<id>test</id>
			<properties>
				<spring.profiles.active>test</spring.profiles.active>
			</properties>
		</profile>
		<!-- 生产环境 -->
		<profile>
			<id>prd</id>
			<properties>
				<spring.profiles.active>prd</spring.profiles.active>
			</properties>
		</profile>
	</profiles>

还是pom.xml文件,build标签里添加

<!-- profile对资源的操作 -->
<resources>
	<resource>
		<directory>src/main/resources</directory>
		<excludes>
			<exclude>application*.properties</exclude>
		</excludes>
	</resource>
	<resource>
		<directory>src/main/resources</directory>
		<!-- 是否替换@xx@表示的maven properties属性值 -->
		<filtering>true</filtering>
		<includes>
			<include>application.properties</include>
			<include>application-${spring.profiles.active}.properties</include>
		</includes>
	</resource>
</resources>

修改application.properties

添加下面内容

[email protected]@

新建不同环境properties,比如以下截图
在这里插入图片描述
在pom.xml中配置的dev、test、prd分别对应了application-*.properties

maven打包命令

mvn clean package -P test

上面-P test参数使得application.properties中的spring.profiles.active=test,即使用application-test.properties配置,没有指定-P test参数时,默认使用了dev环境,这在上面的pom.xml中有体现

在eclipse或idea中run项目的问题

由于application.properties指定了[email protected]@,在eclipse或idea中直接run项目,会提示spring.profiles.active没有定义。解决方法是可以直接定义spring.profiles.active=devdev是我本地配置文件),在需要打包其他环境的时候,修改成[email protected]@,然后指定-P参数进行打包

猜你喜欢

转载自blog.csdn.net/ihtczte/article/details/87085082