Spring基礎—— 在 Spring Config 中使用外部屬性檔案,springconfig

來源:互聯網
上載者:User

Spring基礎—— 在 Spring Config 中使用外部屬性檔案,springconfig

一、在 Spring Config 檔案中配置 Bean 時,有時候需要在 Bean 的配置裡添加 系統部署的細節資訊, 如檔案路徑,資料來源配置資訊。而這些部署細節實際上需要在設定檔外部來定義。

二、Spring 提供了一個 PropertyPlaceholderConfigurer 的 BeanFactory 後置處理器。這個處理器允許使用者將 Bean 的配置部分內容外移到屬性檔案中,然後可以在 Bean 的設定檔

裡使用形式為 ${var}的變數,PropertyPlaceholderConfigurer 從屬性檔案裡載入屬性,並使用這些屬性來替換變數。

三、Spring 還允許在屬性檔案中使用 ${key},以屬性間的互相引用。

四、使用:需要註冊 PropertyPlaceholderConfigurer 。通過 <context:property-placeholder location="props.properties"/> 這種方式來指定屬性檔案。

五、例子:

1.目錄結構

2. spring-config.xml

<context:property-placeholder location="db.properties"/><bean class="com.nucsoft.spring.bean.Employee" id="employee" p:empName="${abc}" p:age="${cde}" scope="prototype"/>

3.db.properties

abc=123456cde=${abc}

4.測試

@Testpublic void test01() {  Employee employee = ctx.getBean(Employee.class);  System.out.println(employee);}

5.控制台輸出

Employee{empName='123456', age=123456}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.