maven profile实现多环境构建 (单项目多套配置)

本文介绍如何使用Maven的profile功能实现不同环境的配置切换,包括开发环境、测试环境及生产环境,通过配置pom.xml文件,使得软件在不同环境下能够灵活地调整配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在使用maven做为构建工具的开发过程中,我们的软件会面对不同的运行环境,比如开发环境、测试环境、生产环境,而我们的软件在不同的环境中,有的配置可能会不一样,比如数据源配置、日志文件配置、以及一些软件运行过程中的基本配置,那每次我们将软件部署到不同的环境时,都需要修改相应的配置文件,这样来回修改,是个很麻烦的事情。
因此我们使用maven来实现多环境的构建可移植性,需要借助maven提供的profile功能,通过不同的环境激活不同的profile来达到构建的可移植性。

打开pom.xml,配置profile

<profiles>
		<profile>
			<!-- 本地开发环境 -->
			<id>develop</id>
			<properties>
				<profiles.active>develop</profiles.active>
			</properties>
			<activation>
				<activeByDefault>true</activeByDefault>
			</activation>
		</profile>
		<profile>
			<!-- 测试环境 -->
			<id>test</id>
			<properties>
				<profiles.active>test</profiles.active>
			</properties>
		</profile>
		<profile>
			<!-- 生产环境 -->
			<id>production</id>
			<properties>
				<profiles.active>production</profiles.active>
			</properties>
		</profile>
	</profiles>


<build>
<resources>
			<resource>
				<directory>src/main/resources</directory>
				<!-- 资源根目录排除各环境的配置,使用单独的资源目录来指定 -->
				<excludes>
					<exclude>config-develop/*</exclude>
					<exclude>config-production/*</exclude>
				</excludes>
			</resource>
			<resource>
				<!-- 根据参数指定资源目录 -->
				<directory>src/main/resources/config-${profiles.active}</directory>
				<!-- 指定编译后的目录即生成文件位置(默认为WEB-INF/class) -->
				<targetPath>config</targetPath>
			</resource>
		</resources>
</build>

项目结构



eclipse maven 打包 



或:

mvn clean package -Pproduction即构建出生产环境需要的war包

mvn tomcat:redeploy -Ptest 即发布到测试环境

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值