根据环境变量,使用maven切换不同的配置文件

前提

项目常见的部署环境:Dev(开发环境)Test(测试环境)Proc(生产环境)

问题

不同环境配置文件的配置往往需要进行一些修改,如果配置文件只有一份且打包在war中,那么在其他环境下就需要进行对应的修改。站在部署的角度,这将会变得非常的不方便。

解决方法

可以通过maven pom.xml提供的 profiles标签 来实现 打包时 指定何种环境的配置文件

步骤

1.在pom.xml中添加 profiles 信息

	<profiles>
		<profile>
                        <!--id唯一,打包时可以通过 -P profile.id 指定profile-->
			<id>Dev</id>
			<properties>
                                <!--自定义标签,等待被${}占位符引用-->
				<profile.active>Dev</profile.active>
			</properties>
			<activation>
				<!--打包时不指定profile,默认使用-->
				<activeByDefault>true</activeByDefault>
			</activation>
		</profile>
		<profile>
			<id>Test</id>
			<properties>
				<profile.active>Test</profile.active>
			</properties>
		</profile>
		<profile>
			<id>Proc</id>
			<properties>
				<profile.active>Proc</profile.active>
			</properties>
		</profile>
	</profiles>

2.排除内部的配置文件,使用占位符传参方式指定profile.id,此处可以使用两种方式

  • 1.将所有环境的配置文件全放在项目(war)中。配置简单
  • 2.将配置文件放在项目(war)外,使用 系统环境变量 指定配置文件夹位置。更灵活,修改外部的文件重新打包即可

第一种方式比较常见,这里不多赘述

3.使用第二种方式实现

环境变量配置如下:

pom.xml中,加入对resources处理。排除内部配置文件,引用外部配置文件(当然,也可以直接将内部配置文件直接移除)

		<resources>
			<resource>
				<directory>src/main/resources/</directory>
				<!--排除内部配置文件,不进行打包-->
				<excludes>
					<exclude>db.properties</exclude>
					<exclude>config.properties</exclude>
				</excludes>
			</resource>
			<resource>
				<!--${ENV_SETTING_HOME}为环境变量,maven中可直接使用${}的方式引用环境变量-->
                                <!--${profile.active}为 profile的具体值-->
				<directory>/${ENV_SETTING_HOME}/${profile.active}</directory>
			</resource>
		</resources>

4.进行打包,指定 profile.id

打包命令行:mvn clean package -P Dev|Test|Proc
使用eclipse有两种方式(其实只是简化了命令行),如下:

原文地址:https://www.cnblogs.com/zhuang229/p/13071094.html