在工作中,開發環境一般和生産環境不同,比如開發Java web應用時我們一般喜歡使用Tomcat等輕量型容器,而在生産環境一般使用像Weblogic這樣的商業重量級容器;單元測試的時候大家喜歡直接使用記憶體資料庫,而生産環境則使用像Oracle這樣的商業資料庫。對于這類問題我們一般需要提供不同的配置資訊,甚至寫不同的建構腳本來支援持續內建工作,如果我們正使用spring架構進行開發,spring 從3.1版本開始為我們提供了一個可選方案,即profile。
什麼是spring profile?簡單講profile就是一組配置,不同profile提供不同組合的配置,程式運作時可以選擇使用哪些profile來适應環境。spring bean 配置是使用spring架構進行開發的一項重要工作,有了profile可以讓開發和測試工作更加條理,下面是用标注配置的一個profile示例:
1
2
3
4
5
<code>@Configuration</code>
<code>@Profile</code><code>(value=</code><code>"productprofile"</code><code>)</code>
<code>public</code> <code>class</code> <code>ProductConfig {</code>
<code>...</code>
<code>}</code>
profile當然同時支援XML和Java檔案标注,可用于class級别也可用于配置檔案級别,或者beans級别。比如我們建立一個unittest profile用于指明單元測試使用,而某個class TestA隻是測試有用,那麼我們可以将其标注unittest profile,這樣如果unittest profile沒有啟用時TestA是不會被spring上下文解析。profile主要用于對bean 配置進行分類貼标簽,筆者建議先将不同環境的配置分類放于不同XML配置檔案(或者java配置類),然後再給各個配置檔案加全局的profile屬性,避免給單個類貼标簽,另外profile确實很靈活,一個配置檔案可以貼多個profile标簽,如
<code><</code><code>beans</code> <code>profile</code><code>=</code><code>"p1,p2"</code><code>></code>
spring提供多種啟用profile的方式:
6
7
8
9
<code>1</code><code>.ENV方式: ConfigurableEnvironment.setActiveProfiles(</code><code>"unittest"</code><code>)</code>
<code>2</code><code>.JVM參數方式: -Dspring.profiles.active=</code><code>"unittest"</code>
<code>3</code><code>.web.xml方式:</code>
<code><init-param></code>
<code> </code><code><param-name>spring.profiles.active</param-name></code>
<code> </code><code><param-value>production</param-value></code>
<code></init-param></code>
<code>4</code><code>.标注方式(junit單元測試非常實用):</code>
<code>@ActiveProfiles({</code><code>"unittest"</code><code>,</code><code>"productprofile"</code><code>})</code>
附件中給了個例子通過啟用不同profile來使用不同的datasource,供大家一起學習參考,謝謝!
<a href="http://down.51cto.com/data/2363944" target="_blank">附件:http://down.51cto.com/data/2363944</a>
本文轉自sarchitect 51CTO部落格,原文連結:http://blog.51cto.com/stevex/1348307,如需轉載請自行聯系原作者