配置環境web
使用也是非的方便。只要在applicationContext.xml中添加下邊的內容,就能夠了spring
<beans profile="develop"> 數據庫
<context:property-placeholder location="classpath*:jdbc-develop.properties"/> app
</beans> ide
<beans profile="production"> 測試
<context:property-placeholder location="classpath*:jdbc-production.properties"/> url
</beans> spa
<beans profile="test"> orm
<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)
<!-- 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>
切換環境
在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
你能夠寫一個基類來寫這個註解,而後讓大家測試類都繼承這個測試基類,會很方便。