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&autoReconnectForPools=true&useUnicode=true&characterEncoding=UTF-8&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里配置的值這種解決方案不僅僅適用于數據庫,任何外部環境配置都可以使用該方案,如對消息服務器的依賴等。
新聞熱點
疑難解答