spring profile 多環境配置管理
spring profile 多環境配置管理
本地、測試、開發、產品等不同環境檔案配置
問題:
如果在開發時進行一些資料庫測試,希望連結到一個測試的資料庫,以避免對開發資料庫的影響。
開發時的某些配置比如log4j日誌的級別,和生產環境又有所區別。各種此類的需求,讓我希望有一個簡單的切換開發環境的好辦法。
解決:
現在spring3.1也給我們帶來了profile,可以方便快速的切換環境。
使用也是非常方便。只要在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的結構大概是這樣:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:c="http://www.springframework.org/schema/c" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd"> <description>spring profile配置</description> <!-- 開發環境配置檔案 --> <beans profile="development"> <context:property-placeholder location="classpath*:common/*.properties, classpath*:development/*.properties" /> </beans> <!-- 測試環境配置檔案 --> <beans profile="test"> <context:property-placeholder location="classpath*:common/*.properties, classpath*:test/*.properties" /> </beans> <!-- 生產環境配置檔案 --> <beans profile="production"> <context:property-placeholder location="classpath*:common/*.properties, classpath*:production/*.properties" /> </beans> </beans>
啟用 profile
spring 為我們提供了大量的啟用 profile 的方法,可以通過程式碼來啟用,也可以通過系統環境變數、JVM引數、servlet上下文引數來定義 spring.profiles.active 引數啟用 profile,這裡我們通過定義 JVM 引數實現。
1、ENV方式:
ConfigurableEnvironment.setActiveProfiles("test")
2、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"
3、web.xml方式:
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>spring.profiles.default</param-name>
<param-value>development</param-value>
</init-param>
</servlet>
或:
<context-param>
<param-name>spring.profiles.default</param-name>
<param-value>development</param-value>
</context-param>
4、標註方式(junit單元測試非常實用):
@ActiveProfiles({"unittest","productprofile"})