若是在開發時進行一些數據庫測試,但願連接到一個測試的數據庫,以免對開發數據庫的影響。web
開發時的某些配置好比log4j日誌的級別,和生產環境又有所區別。spring
各類此類的需求,讓我但願有一個簡單的切換開發環境的好辦法,曾經在ROR的時候就很喜歡舒服。sql
如今spring3.1也給咱們帶來了profile,能夠方便快速的切換環境。數據庫
配置環境app
使用也是非的方便。只要在applicationContext.xml中添加下邊的內容,就能夠了ide
<beans profile="develop"> <context:property-placeholder location="classpath*:jdbc-develop.properties"/> </beans> <beans profile="production"> <context:property-placeholder location="classpath*:jdbc-production.properties"/> </beans> <beans profile="test"> <context:property-placeholder location="classpath*:jdbc-test.properties"/> </beans>
profile的定義必定要在文檔的最下邊,不然會有異常。整個xml的結構大概是這樣的,測試
<beans xmlns="..." ...> <bean id="dataSource" ... /> <bean ... /> <beans profile="..."> <bean ...> </beans> </beans>
我經過給不一樣的環境,引入不一樣的properties來設置不一樣的屬性,你也能夠直接在bean裏進行定義一些特殊的屬性,好比下邊這樣,在test的時候,初始化數據庫與默認數據。(代碼摘錄:springside)url
<!-- unit test環境 --> <beans profile="test"> <context:property-placeholder ignore-resource-not-found="true" location="classpath*:/application.properties, classpath*:/application.test.properties" /> <!-- Simple鏈接池 --> <bean id="dataSource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource"> <property name="driverClass" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </bean> <!-- 初始化數據表結構 與默認數據--> <jdbc:initialize-database data-source="dataSource" ignore-failures="ALL"> <jdbc:script location="classpath:sql/h2/schema.sql" /> <jdbc:script location="classpath:data/import-data.sql" encoding="UTF-8"/> </jdbc:initialize-database> </beans>
切換環境spa
在web.xml中添加一個context-param來切換當前環境:日誌
<context-param> <param-name>spring.profiles.active</param-name> <param-value>develop</param-value> </context-param>
若是是測試類可使用註解來切換:
@ActiveProfiles("test")
測試類大概是這個樣子:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:applicationContext.xml") @ActiveProfiles("test") public class DictionaryServiceTest extends AbstractTransactionalJUnit4SpringContextTests
你能夠寫一個基類來寫這個註解,而後讓大家測試類都繼承這個測試基類,會很方便。