在实际开发过程中通常有多个环境,比如本地环境(local),开发环境(dev),测试环境(uat),生产环境(prod)
不同环境的配置可能不同,比如数据库的配置,redis,activeMQ的配置,当和其它平台对接的时候,一般不同的环境也有不同的接口。在代码中需要用到这些配置信息,有时候还需要用这些配置信息做逻辑判断,比如系统涉及到支付的时候,开发和测试环境只需要支付0.01即可,走一个支付流程就可以了,在生产环境才需要完全按照实际来
利用maven可以实现在打包的时候动态选择配置文件, 达到同样的源代码,在不同环境下打包后的配置文件不同的目的.
1.打包的时候选择环境
1. 利用profile标签
<profiles>
<profile>
<id>local</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<envCode>local</envCode>
</properties>
</profile>
<profile>
<id>dev</id>
<activation />
<properties>
<envCode>dev</envCode>
</properties>
</profile>
</profiles>
打包的时候 mvn clean install -Plocal
maven会根据上面配置的profile的id去匹配profile,每个profile又有不同的properties,以实现不同的环境有不同的配置
2. 直接利用properties标签
<properties>
<junit.version>4.12</junit.version>
<spring.version>5.1.4.RELEASE</spring.version>
<jackson.verson>2.9.8</jackson.verson>
<envCode>local</envCode>
</properties>
上图中直接在properties标签中定义了 envCode(默认为local)
打包的时候 mvn clean install -DenvCode=local 不同环境直接传入不同的参数即可
2.不同环境使用不同配置文件
1. 利用resource标签的目录映射来实现
目录结构如下:
dev/config/properties 中 envCode=dev
local/config/properties 中 envCode=local
pom文件配置
<build>
<finalName>SpringProject</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>properties/local/*</exclude>
<exclude>properties/dev/*</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/resources/properties/${envCode}</directory>
<targetPath>${basedir}/target/classes/properties</targetPath>
</resource>
</resources>
</build>
mvn clean install -plocal target/classes/properties下是 src/main/resource/properties/local/config.properties
mvn clean install -Pdev target/classes/properties下是 src/main/resource/properties/dev/config.properties
2. 利用filter实现
目录
增加了 config.properties 内容为: envCode=${envCode}
pom文件配置
<build>
<finalName>SpringProject</finalName>
<filters>
<filter>src/main/resources/properties/${envCode}/config.properties</filter>
</filters>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
打包后,config.properties中 ${envCode}会使用相应被过滤的配置文件中的属性值替代。
方法1中利用目录映射,切换环境时,直接使用了不同的文件
方法2中切换环境,使用的都是同一个文件,但是文件中定义的属性值会动态改变