spring3.1 profile 配置不一樣的環境

配置環境web

使用也是非的方便。只要在applicationContext.xml中添加下邊的內容,就能夠了spring

 

Java代碼  收藏代碼sql

  1. <beans profile="develop">  數據庫

  2.         <context:property-placeholder location="classpath*:jdbc-develop.properties"/>  app

  3.     </beans>  ide

  4.     <beans profile="production">  測試

  5.         <context:property-placeholder location="classpath*:jdbc-production.properties"/>  url

  6.     </beans>  spa

  7.     <beans profile="test">  orm

  8.         <context:property-placeholder location="classpath*:jdbc-test.properties"/>  

  9.     </beans>  

profile的定義必定要在文檔的最下邊,不然會有異常。整個xml的結構大概是這樣的,

   

Java代碼  收藏代碼

  1. <beans xmlns="..." ...>  

  2.   <bean id="dataSource" ... />  

  3.   <bean ... />  

  4.   <beans profile="...">  

  5.     <bean ...>  

  6.   </beans>  

  7. </beans>  

 我經過給不一樣的環境,引入不一樣的properties來設置不一樣的屬性,你也能夠直接在bean裏進行定義一些特殊的屬性,好比下邊這樣,在test的時候,初始化數據庫與默認數據。(代碼摘錄:springside)

Java代碼  收藏代碼

  1. <!-- unit test環境 -->  

  2.     <beans profile="test">  

  3.         <context:property-placeholder ignore-resource-not-found="true"  

  4.             location="classpath*:/application.properties,  

  5.                       classpath*:/application.test.properties" />      

  6.           

  7.         <!-- Simple鏈接池 -->  

  8.         <bean id="dataSource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">  

  9.             <property name="driverClass" value="${jdbc.driver}" />  

  10.             <property name="url" value="${jdbc.url}" />  

  11.             <property name="username" value="${jdbc.username}" />  

  12.             <property name="password" value="${jdbc.password}" />  

  13.         </bean>  

  14.   

  15.         <!-- 初始化數據表結構 與默認數據-->  

  16.         <jdbc:initialize-database data-source="dataSource" ignore-failures="ALL">  

  17.             <jdbc:script location="classpath:sql/h2/schema.sql" />  

  18.             <jdbc:script location="classpath:data/import-data.sql" encoding="UTF-8"/>  

  19.         </jdbc:initialize-database>  

  20.     </beans>  

 切換環境

  在web.xml中添加一個context-param來切換當前環境:

Java代碼  收藏代碼

  1. <context-param>  

  2.     <param-name>spring.profiles.active</param-name>  

  3.     <param-value>develop</param-value>  

  4. </context-param>  

 若是是測試類能夠使用註解來切換:

Java代碼  收藏代碼

  1. @ActiveProfiles("test")  

 測試類大概是這個樣子:

Java代碼  收藏代碼

  1. @RunWith(SpringJUnit4ClassRunner.class)  

  2. @ContextConfiguration(locations = "classpath:applicationContext.xml")  

  3. @ActiveProfiles("test")  

  4. public class DictionaryServiceTest extends AbstractTransactionalJUnit4SpringContextTests  

 你能夠寫一個基類來寫這個註解,而後讓大家測試類都繼承這個測試基類,會很方便。

相關文章
相關標籤/搜索