spring profile 多環(huán)境配置管理詳解
spring profile 多環(huán)境配置管理
現(xiàn)象
如果在開發(fā)時(shí)進(jìn)行一些數(shù)據(jù)庫測試,希望鏈接到一個(gè)測試的數(shù)據(jù)庫,以避免對開發(fā)數(shù)據(jù)庫的影響。
開發(fā)時(shí)的某些配置比如log4j日志的級別,和生產(chǎn)環(huán)境又有所區(qū)別。
各種此類的需求,讓我希望有一個(gè)簡單的切換開發(fā)環(huán)境的好辦法。
解決
現(xiàn)在spring3.1也給我們帶來了profile,可以方便快速的切換環(huán)境。
使用也是非常方便。只要在applicationContext.xml中添加下邊的內(nèi)容,就可以了
<!-- 開發(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的定義一定要在文檔的最下邊,否則會(huì)有異常。整個(gè)xml的結(jié)構(gòu)大概是這樣
<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ù)實(shí)現(xiàn)。
1、ENV方式:
ConfigurableEnvironment.setActiveProfiles("test")
2、JVM參數(shù)方式:
tomcat 中 catalina.bat(.sh中不用“set”) 添加JAVA_OPS。通過設(shè)置active選擇不同配置文件
set JAVA_OPTS="-Dspring.profiles.active=test"
eclipse 中啟動(dòng)tomcat。項(xiàng)目右鍵 run as –> run configuration–>Arguments–> VM arguments中添加。local配置文件不必上傳Git追蹤管理
-Dspring.profiles.active="local"
3、web.xml方式:
<init-param> <param-name>spring.profiles.active</param-name> <param-value>production</param-value> </init-param>
4、標(biāo)注方式(junit單元測試非常實(shí)用):
@ActiveProfiles({"unittest","productprofile"})
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
IDEA的Web項(xiàng)目右鍵無法創(chuàng)建Servlet問題解決辦法
這篇文章主要介紹了IDEA的Web項(xiàng)目右鍵無法創(chuàng)建Servlet問題解決辦法的相關(guān)資料,在IDEA中新建Servlet時(shí)發(fā)現(xiàn)缺失選項(xiàng),可以通過在pom.xml文件中添加servlet依賴解決,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下2024-10-10Springboot整合freemarker和相應(yīng)的語法詳解
FreeMarker是一款Spring官方推薦使用的模板引擎。接下來通過本文給大家介紹Springboot整合freemarker和相應(yīng)的語法,感興趣的朋友一起看看吧2021-09-09Java中this和super的區(qū)別及this能否調(diào)用到父類使用
這篇文章主要介紹了Java中this和super的區(qū)別及this能否調(diào)用到父類使用,this和super都是Java中常見的關(guān)鍵字,下文關(guān)于兩者區(qū)別介紹,需要的小伙伴可以參考一下2022-05-05JSON序列化導(dǎo)致Long類型被搞成Integer的坑及解決
這篇文章主要介紹了JSON序列化導(dǎo)致Long類型被搞成Integer的坑及解決方案,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-01-01