若是在開發時進行一些數據庫測試,但願連接到一個測試的數據庫,以免對開發數據庫的影響。java
開發時的某些配置好比log4j日誌的級別,和生產環境又有所區別。web
各類此類的需求,讓我但願有一個簡單的切換開發環境的好辦法,曾經在ROR的時候就很喜歡舒服。spring
如今spring3.1也給咱們帶來了profile,能夠方便快速的切換環境。數據庫
一、配置環境app
使用也是非的方便。只要在applicationContext.xml中添加下邊的內容,就能夠了測試
<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的結構大概是這樣的,
spa
我經過給不一樣的環境,引入不一樣的properties來設置不一樣的屬性,你也能夠直接在bean裏進行定義一些特殊的屬性,好比下邊這樣,在test的時候,初始化數據庫與默認數據.日誌
二、切換環境code
在web.xml中添加一個context-param來切換當前環境:orm
<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
你能夠寫一個基類來寫這個註解,而後讓大家測試類都繼承這個測試基類,會很方便。