maven环境隔离

在maven实际使用过程中,可以对环境进行不同的配置隔离,方便线上,测试,本地环境的不同部署,避免了手动修改配置文件的麻烦,而且容易出错和遗漏。下面记录一下环境隔离的相关配置操作。

隔离配置及原理

新增resource节点

pom.xml文件的build节点中增加如下的配置

1
2
3
4
5
6
7
8
9
10
11
<resources>
<resource>
<directory>src/main/resources.${deploy.type}</directory>
<excludes>
<exclude>*.jsp</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>

该节点用于配制打包过程中的相关资源属性,此处使用${deploy.type}声明一个变量来指定不同的打包目录

新增profiles节点

pom.xml中新增profiles节点,配置如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

<profiles>
<profile>
<id>dev</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<deploy.type>dev</deploy.type>
</properties>
</profile>
<profile>
<id>beta</id>
<properties>
<deploy.type>beta</deploy.type>
</properties>
</profile>
<profile>
<id>prod</id>
<properties>
<deploy.type>prod</deploy.type>
</properties>
</profile>
</profiles>

前面resource中的变量来自于此,根据不同的id,将得到不同的deploy.type。另外,在节点中增加activation节点,可以指定默认激活的选项

新建对应文件夹

将需要隔离的文件分开,公共的留下来,在resource节点下的directory指明了需要打包的路径,因此新建的文件夹将和上面配置的一一对应,类似如下结构

在IDEA开发环境中可以选择对应的环境配置

隔离后的打包命令

1
2

mvn clean package -Dmaven.test.skip=true -Pdev

主要在于-P参数,指定对应环境