以数据库连接配置为例:
1、使用Maven自定义属性将可能变化的内容提取出来,如jdbc.properties文件内容如下:
jdbc.database.driver=${db.driver}
jdbc.database.url=${db.url}
jdbc.database.username=${db.username}
jdbc.database.password=${db.password}
2、在pom.xml文件中定义profile,定义多个环境,如下:
<profiles>
<profile>
<id>dev</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<db.driver>com.mysql.jdbc.Driver</db.driver>
<db.url>jdbc:mysql://localhost:3306/dev</db.url>
<db.username>dev-root</db.username>
<db.password>dev-pwd</db.password>
</properties>
</profile>
<profile>
<id>test</id>
<properties>
<db.driver>com.mysql.jdbc.Driver</db.driver>
<db.url>jdbc:mysql://localhost:3306/test</db.url>
<db.username>test-root</db.username>
<db.password>test-pwd</db.password>
</properties>
</profile>
</profiles>
其中,定义了一个dev(开发环境)、一个test(测试环境)的profile;
在dev中,activation表示默认激活dev的profile;
3、让Maven解析资源文件中的Maven自定义属性
在pom.xml文件中做如下修改:
<build>
<!-- 为主资源目录开启过滤 -->
<resources>
<resource>
<directory>${project.basedir}/src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<!-- 为测试资源目录开启过滤 -->
<testResources>
<testResource>
<directory>${project.basedir}/src/test/resources</directory>
<filtering>true</filtering>
</testResource>
</testResources>
</build>
maven-resources-plugin将项目主资源文件复制到主代码编译数据目录中,将测试资源文件复制到测试代码编译输出目录中;通过以上的过滤配置,该插件就能解析资源文件中的Maven属性,即开启资源过滤;
4、在命令中激活profile
$mvn clean install/compile -Pdev
$mvn clean install/compile -Ptest
运行以上命令,即可在看到该文件:
{工程所在路径}\target\classes\jdbc.properties
里面的Maven自定义标签已经被替换为在pom.xml文件中定义的相应内容了;