Spring學習筆記 在XML配置檔案中使用properties檔案的鍵值
阿新 • • 發佈:2019-01-22
property檔案可以很方便的在部署執行階段改變一些特定配置屬性,比如資料庫連線等。然後在程式中根據鍵名使用property檔案中的特定屬性。在Spring中也可以在XML配置檔案中的Bean定義時通過property檔案動態進行屬性值的定義。
使用方法描述
假如入在property檔案中有以下屬性
db.url=jdbc:oracle:thin:@127.0.0.1:1521:test
那麼在XML中就可以使用 ${db.url} 進行引用。
具體實現
第一步:在XML配置檔案中註冊我們將要在XML中使用的properties檔案
-
<!-- 我們不會將這個Bean進行例項化,class屬性中定義了PropertyPlaceholderConfigurer類,可以告訴Spring我們實際上要註冊一個properties檔案-->
- <beanid="propertyFileConfigForDB"
- class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
- <propertyname="location">
- <value>dbconfig.properties</value>
- <!-- 以上為properties檔案路徑-->
- </property>
- </bean>
第二步:在XML中使用properties檔案中定義的值
- <beanname="dataSource"
- class="test.DataSource">
- <!--這裡通過 ${} 的方式引用properties檔案中定義的db.url的值 -->
- <propertyname="url"value='${db.url}'/>
- </bean>
第三步:建立properties檔案,並在其中寫入我們要呼叫的鍵值對
- db.url = jdbc:oracle:thin:@127.0.0.1:1521:orcl
另外有人知道如何通過properties檔案對Bean中Map型別屬性進行初始化嗎?上網沒找到示例,我臨時使用init在初始化bean的時候手動初始化了Map。