Maven 项目实现多环境配置文件

   在 Spring boot 项目中,我们已经习惯了多环境配置文件的使用。最近在维护旧项目时,因运行环境较多,一时起念,非 Spring boot 项目能实现多环境配置文件的配置和切换吗?经过查找资料,发现 Maven 早已提供了 profile 来实现多环境配置。真是孤陋寡闻,记录以学习之。


方式一:filter 方式

  1. 编写多环境配置文件,分别定义主配置文件 application.properties 和两个环境配置文件application-dev.propertiesapplication-test.properties
  • application.properties
1
jdbc.username=${env.jdbc.username}
  • application-dev.properties
1
env.jdbc.username=dev
  • application-test.properties
1
env.jdbc.username=test

由上面文件中看到,我们在主配置文件并未定义实际值,而是引用环境配置中对应 key 的值。

  1. 在 pom.xml 中配置 profile:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<profiles>
<profile>
<id>dev</id>
<properties>
<env>dev</env>
</properties>
<activation>
<!-- 默认激活 -->
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>test</id>
<properties>
<env>test</env>
</properties>
</profile>
</profiles>

由上面文件中看到,我们配置了两套环境配置 dev 和 test。

  1. 在 pom.xml 中配置 filter 和 resource:
1
2
3
4
5
6
7
8
9
10
11
<build>
<filters>
<filter>src/main/resources/application-${env}.properties</filter>
</filters>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>

注意:<filtering>true</filtering>不可遗漏。

  1. 打包运行:
1
2
3
4
5
# 不指定运行环境,默认是 activeByDefault=true的环境,当前是指开发环境 
mvn package

# 指定运行环境,`<env>` 指 dev/test,注意参数 P 是大写
mvn package -P <env>

打包执行完成后,我们在 target 目录下的 applincation.properties 中可以看到值是随着指定运行环境变化的。

方式二:resource 方式

  1. 在 resources 下建立多个环境目录放置各自的配置文件:
  • env/dev/application.properties
1
jdbc.username=dev
  • env/test/application.properties
1
jdbc.username=test
  1. 在 pom.xml 中配置 profile:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<profiles>
<profile>
<id>dev</id>
<properties>
<env>dev</env>
</properties>
<activation>
<!-- 默认激活 -->
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>test</id>
<properties>
<env>test</env>
</properties>
</profile>
</profiles>

由上可以看出,两种方式在这一步是一致的,区别主要在下一步。

  1. 在 pom.xml 中配置 resource:
1
2
3
4
5
6
7
8
9
10
11
12
13
<build>
<resources>
<resource>
<directory>${basedir}/src/resources/env/${env}</directory>
<includes>
<include>*/*.xml</include>
<include>*/*.properties</include>
<include>*.xml</include>
<include>*.properties</include>
</includes>
</resource>
</resources>
</build>
  1. 打包运行:
    和方式一一样的操作,打包后,可以看到只有一套配置文件出现在 target 目录里。

小结

  1. 方式一,会把多个环境的配置文件都打包进去,且主要针对属性文件,如果有多个文件或者其他类型文件,这种方式是不容易处理的;
  2. 方式二,只打包指定环境的配置文件,且会打包整个文件夹,更方便一点;
  3. 展开一下思路,Springboot 其实是类似方式一的,如果 Springboot 项目想要只打包指定环境的配置文件,可以和方式二结合一下,一起处理。