spring profile 多環境配置管理

現象

  若是在開發時進行一些數據庫測試,但願連接到一個測試的數據庫,以免對開發數據庫的影響。html

  開發時的某些配置好比log4j日誌的級別,和生產環境又有所區別。git

  各類此類的需求,讓我但願有一個簡單的切換開發環境的好辦法。web

解決

  如今spring3.1也給咱們帶來了profile,能夠方便快速的切換環境。spring

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

<!-- 開發環境配置文件 -->
    <beans profile="test">
        <context:property-placeholder location="/WEB-INF/test-orm.properties" />
    </beans>

    <!-- 本地環境配置文件 -->
    <beans profile="local">
        <context:property-placeholder location="/WEB-INF/local-orm.properties" />
    </beans> 

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

<beans xmlns="..." ...>  
  <bean id="dataSource" ... />  
  <bean ... />  
  <beans profile="...">  
    <bean ...>  
  </beans>  
</beans> 

激活 profile

在web.xml裏定義使用的profile,最聰明的作法是定義成context-param,注意這裏定義的是default值,在非生產環境,能夠用系統變量"spring.profiles.active"進行覆蓋。app

<context-param>  
  <param-name>spring.profiles.default</param-name>  
  <param-value>production</param-value>  
</context-param> 

 

spring 爲咱們提供了大量的激活 profile 的方法,能夠經過代碼來激活,也能夠經過系統環境變量、JVM參數、servlet上下文參數來定義 spring.profiles.active 參數激活 profile,這裏咱們經過定義 JVM 參數實現。eclipse

一、ENV方式

ConfigurableEnvironment.setActiveProfiles("test") 

二、JVM參數方式

  tomcat 中 catalina.bat(.sh中不用「set」) 添加JAVA_OPS。經過設置active選擇不一樣配置文件單元測試

set JAVA_OPTS="-Dspring.profiles.active=test" 

  eclipse 中啓動tomcat。項目右鍵 run as –> run configuration–>Arguments–> VM arguments中添加。local配置文件沒必要上傳git追蹤管理測試

-Dspring.profiles.active="local" 

三、web.xml方式

<init-param>
  <param-name>spring.profiles.active</param-name>
  <param-value>production</param-value>
</init-param>

四、標註方式

junit單元測試很是實用

@ActiveProfiles({"unittest","productprofile"})

 參考資料

https://www.cnblogs.com/pangguoming/p/5888871.html

http://nassir.iteye.com/blog/1535799/

相關文章
相關標籤/搜索