Maven 使用Profile和Resources Filter隔离测试环境

Maven能够帮我们很好的管理测试,我们可以在 src/test/java 和 src/test/resources 下面使用JUnit或者TestNG 编写单元测试和集成测试,然后在命令行运行 mvn test ,

当我们的项目开发人员很多的时候,那么问题来了,如何进行测试环境隔离呢,比如dataSource的配置  ,有些配置本地的数据库,而有些配置测试环境或生产环境的,频繁的签入签出很困扰,

maven使用Profile和Resources Filter隔离测试环境可以解决此问题,以下是解决方案:

首先在maven的安装目录下的settings.xml

<profile>
<id>mySqlProfile</id>
<properties>
<mysql.url>jdbc:mysql://localhost:3306</mysql.url>
<mysql.username>test</mysql.username>
<mysql.password>test</mysql.password>
<mysql.dbname>test</mysql.dbname>
</properties>
</profile>

<activeProfiles>
<!--make the profile active all the time -->
<activeProfile>mySqlProfile</activeProfile>
</activeProfiles>

然后配置SpringHibernate.xml

<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName"
value="com.mysql.jdbc.Driver">
</property>
<property name="url"
value="jdbc:mysql://${mysql.url}/${mysql.dbname}?autoReconnect=true&amp;autoReconnectForPools=true&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;mysqlEncoding=utf-8">
</property>
<property name="username" value="${mysql.username}"></property>
<property name="password" value="${mysql.password}"></property>
<property name="maxActive" value="100"></property>
<property name="maxIdle" value="50"></property>
<property name="maxWait" value="10000"></property>
<!--1 hours-->
<property name="timeBetweenEvictionRunsMillis" value="3600000"></property>
<!--<property name="minEvictableIdleTimeMillis" value="20000"></property>-->
<property name="testWhileIdle" value="true"></property>
<property name="validationQuery" value="select 1 from dual"></property>
</bean>

最后,不要忘了配置 Maven Resources 插件让它开启 filtering 功能:

在你要发布的web项目的pom.xml里

<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>

至此,我们已经把环境相关的变量隔离开了,每个用户都有自己的settings.xml 文件,所以每个人都能配置自己的settings.xml 来使用他想要使用的数据库。

项目发布后maven会自动更新SpringHibernate.xml里配置的值
这种解决方案不仅仅适用于数据库,任何外部环境配置都可以使用该方案,如对消息服务器的依赖等。

原文地址:https://www.cnblogs.com/xiaofeilee/p/4126242.html