文章目录
  1. 1. pom.xml配置
  2. 2. 不同环境的配置文件位置
  3. 3. 打包

在Java项目中通常会有各种配置文件,例如有xml、properties。在不同的环境下配置文件的内容可能会不一样,例如正式环境、测试环境、开发环境连的不是同一个数据库,访问的接口不一样,或者日志的级别不同。如果每次部署不同环境时都要改配置文件的各种配置是非常麻烦的。在这种情况下,可以将这些配置文为每个环境复制一个,分别配置不同的内容,打包部署时不同环境的包中打入对应的配置文件。下面是一个通过Maven的profile结合Maven AntRun Plugin实现的方案。

pom.xml配置

在Maven项目的pom.xml中加入以下配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<profiles>
<profile>
<id>product</id>
<build>
<plugins>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.8</version>
<executions>
<execution>
<phase>compile</phase>
<configuration>
<target>
<copy todir="${basedir}/target/classes/" overwrite="true">
<fileset dir="${basedir}/src/main/resources/distribute/product/" />
</copy>
</target>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>test</id>
<build>
<plugins>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.8</version>
<executions>
<execution>
<phase>compile</phase>
<configuration>
<target>
<copy todir="${basedir}/target/classes/" overwrite="true">
<fileset dir="${basedir}/src/main/resources/distribute/test/" />
</copy>
</target>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>

上面的配置中加入了id为product、test两个profile,分别表示正式环境和测试环境,两块的配置基本相同,只看其中之一即可。其中profile的id可以自定义,如果除了这两个环境外还有其他环境的话可以自行添加。

在每个profile中使用了maven-antrun-plugin插件,<phase>compile</phase>表示在编译阶段,<target>...</target>表示要执行的任务。即在编译是将dir="${basedir}/src/main/resources/distribute/product/"目录下的文件拷贝到todir="${basedir}/target/classes/"目录中,overwrite="true"表示如果文件重复则覆盖。

不同环境的配置文件位置

如果项目中有配置文件,一般是放在src/main/resources目录下:
配置文件目录结构
在src/main/resources目录下新建distribute/product和distribute/test目录,将跟环境相关的配置文件复制到这两个目录中,根据环境修改配置文件内容。完成后目录结构如下:
配置文件目录结构

打包

Maven打包使用mvn package命令,如果是打不同环境的包,可以加上参数-P加上profile的id,例如正式环境可以通过mvn package -P product来打包,测试环境可以通过mvn package -P test来打包,此时就会执行profile中配置的maven-antrun-plugin插件,完成配置文件的拷贝和覆盖,最终打出来的包中的配置文件是这个环境对应的配置。

文章目录
  1. 1. pom.xml配置
  2. 2. 不同环境的配置文件位置
  3. 3. 打包