spring profile 多環(huán)境配置管理
現(xiàn)象
如果在開發(fā)時進(jìn)行一些數(shù)據(jù)庫測試,希望鏈接到一個測試的數(shù)據(jù)庫,以避免對開發(fā)數(shù)據(jù)庫的影響。
開發(fā)時的某些配置比如log4j日志的級別,和生產(chǎn)環(huán)境又有所區(qū)別。
各種此類的需求,讓我希望有一個簡單的切換開發(fā)環(huán)境的好辦法。
解決
現(xiàn)在spring3.1也給我們帶來了profile,可以方便快速的切換環(huán)境。
使用也是非常方便。只要在applicationContext.xml中添加下邊的內(nèi)容,就可以了
1
2
3
4
5
6
7
8
9
|
<!-- 開發(fā)環(huán)境配置文件 --> < beans profile = "test" > < context:property-placeholder location = "/WEB-INF/test-orm.properties" /> </ beans > <!-- 本地環(huán)境配置文件 --> < beans profile = "local" > < context:property-placeholder location = "/WEB-INF/local-orm.properties" /> </ beans > |
profile的定義一定要在文檔的最下邊,否則會有異常。整個xml的結(jié)構(gòu)大概是這樣
1
2
3
4
5
6
7
|
< beans xmlns = "..." ...> < bean id = "dataSource" ... /> < bean ... /> < beans profile = "..." > < bean ...> </ beans > </ beans > |
激活 profile
spring 為我們提供了大量的激活 profile 的方法,可以通過代碼來激活,也可以通過系統(tǒng)環(huán)境變量、JVM參數(shù)、servlet上下文參數(shù)來定義 spring.profiles.active 參數(shù)激活 profile,這里我們通過定義 JVM 參數(shù)實現(xiàn)。
1、ENV方式:
1
|
ConfigurableEnvironment.setActiveProfiles( "test" ) |
2、JVM參數(shù)方式:
tomcat 中 catalina.bat(.sh中不用“set”) 添加JAVA_OPS。通過設(shè)置active選擇不同配置文件
1
|
set JAVA_OPTS= "-Dspring.profiles.active=test" |
eclipse 中啟動tomcat。項目右鍵 run as –> run configuration–>Arguments–> VM arguments中添加。local配置文件不必上傳Git追蹤管理
1
|
-Dspring.profiles.active= "local" |
3、web.xml方式:
1
2
3
4
|
< init-param > < param-name >spring.profiles.active</ param-name > < param-value >production</ param-value > </ init-param > |
4、標(biāo)注方式(junit單元測試非常實用):
1
|
@ActiveProfiles ({ "unittest" , "productprofile" }) |
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
原文鏈接:http://blog.csdn.net/jenny8080/article/details/53185178