思路
- 利用Profile的占位符替换,来实现同一变量不同值的赋值。
- 利用Resource根据当前环境的变量,来实现不同文件的过滤和替换。
实现
方法一
maven自动替换文件中的占位符,从而实现根据maven profie来实现值替换
示例
jdbc.properties
jdbc.url = ${jdbc.url}
jdbc.username = ${jdbc.username}
jdbc.password = ${jdbc.password}
pom.xml 片段
<profiles>
<profile>
<id>dev</id>
<properties>
<env>dev</env>
<jdbc.url>devurl</jdbc.url>
<jdbc.username>devuser</jdbc.username>
<jdbc.password>devpassword</jdbc.password>
</properties>
</profile>
<profile>
<id>test</id>
<properties>
<env>test</env>
<jdbc.url>testurl</jdbc.url>
<jdbc.username>testuser</jdbc.username>
<jdbc.password>testpassword</jdbc.password>
</properties>
</profile>
</profiles>
<build>
<finalName>maven</finalName>
<resources>
<resource>
<directory>${basedir}/src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
</plugin>
</plugins>
</build>
执行命令
# 命令参数示例
mvn pacakge -P[profileId]
# 开发环境
mvn package -Pdev
# 测试环境
mvn package -Ptest
运行结果
- mvn package -Pdev
jdbc.url = devurl
jdbc.username = devuser
jdbc.password = devpassword
- mvn package -Ptest
jdbc.url = testurl
jdbc.username = testuser
jdbc.password = testpassword
方法二
TODO