当开发一个复杂项目时,会涉及到不同的阶段。比如dev, test 及prod阶段。不同阶段,需要不同的环境变量。
那么,如何在不改动代码和配置的前提下实现这个功能?
maven 的profile这时就派上上了用场。
我们以资源文件的copy作为一个例子。
资源文件是用来存放程序在运行期间的各种变量。
假如,在开发的dev, test 及prod的三个阶段,各阶段涉及到的资源文件内容有所差异。我们的目标是,根据不同的阶段,只需要copy相应阶段的资源文件。
假设我文件目录如下:
resources下的子文件dev/test/pro的env.properties内容各不相同。目标是:在dev阶段,只copy dev/env.properties;在test阶段, 只copy test/eb=env.properties;在pro阶段,只copy pro/env.properties.
好了。直接上pom文件:
<?xml version="1.0" encoding="UTF-8"?>
4.0.0
<groupId>org.example</groupId>
<artifactId>second_project</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.1</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources/${profiles.activation}</directory>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.1</version>
<executions>
<execution>
<id>id.pre-clean</id>
<phase>pre-clean</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<echo>pre-clean phase</echo>
</tasks>
</configuration>
</execution>
<execution>
<id>id.clean</id>
<phase>clean</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<echo>clean phase</echo>
</tasks>
</configuration>
</execution>
<execution>
<id>id.post-clean</id>
<phase>post-clean</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<echo>post-clean phase</echo>
</tasks>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>dev</id>
<properties>
<profiles.activation>dev</profiles.activation>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>test</id>
<properties>
<profiles.activation>test</profiles.activation>
</properties>
</profile>
<profile>
<id>pro</id>
<properties>
<profiles.activation>pro</profiles.activation>
</properties>
</profile>
</profiles>
注意到,pom文件声明了三个profile. 每个profile 都声明了一个profiles.activation属性,但值不同。默认下,我设置了id为dev的profile是激活(启用状态)。
在build的resource声明处,引用了profiles.activation这个属性。意思是,该resource的directory的具体值根据激活的profile的不同而不同。
运行三条命令:
命令1: mvn compile
效果: dev/env.properties被copy到target/classes下
命令2: mvn compile -P test
效果: test/env.properties被copy到target/classes下
命令3: mvn compile -P pro
效果: pro/env.properties被copy到target/classes下
大家有兴趣可以做个测试