spring中的PropertyPlaceholderConfigurer作用,用法

來源:互聯網
上載者:User
Spring的架構中為您提供了一個  BeanFactoryPostProcessor  的類: org.springframework.beans.factory.config.PropertyPlaceholderConfigurer。通過這個類,您可以將一些組態設定,移出至.properties檔案中,而.properties檔案可以作為客戶根據需求,自訂一些相關的參數。
來看一個Bean定義檔的實際例子: 
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xmlns:p="http://www.springframework.org/schema/p"    xmlns:context="http://www.springframework.org/schema/context"    xmlns:aop="http://www.springframework.org/schema/aop"    xsi:schemaLocation="        http://www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd        http://www.springframework.org/schema/context        http://www.springframework.org/schema/context/spring-context-3.0.xsd        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"><bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><property name="fileEncoding" value="GBK" /> <property name="locations"><list><value>classpath:mailsender.properties</value></list></property></bean><bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl" ><property name="host"><value>${mail.host}</value></property><property name="port"><value>${mail.port}</value></property><property name="javaMailProperties">            <props>              <prop key="mail.smtp.auth">false</prop>              <prop key="mail.smtp.timeout">25000</prop>            </props>        </property><property name="username"><value>${mail.username}</value></property><property name="password"><value>${mail.password}</value></property></bean></beans>

這是一個發送郵件的demo(但這篇文章主旨不在講述怎麼發送郵件,而是將這個拿出來做為例子),
在mailSender中有許多依賴注入的屬性,這些都是比較不常變動的屬性,但是他的值可能經常會要變動,有時客戶需求需要改變,可以透過mailsender.properties來簡單的設定,而這個資訊已設定在location屬性中: 
mail.transport.protocol=smtp
mail.host=stmp.qq.com
mail.port=25
mail.username=xxxxxxxx@qq.com
mail.password=xxxxxxxx
通過你配置了PropertyPlaceholderConfigurer這個bean,就可以動態擷取這些。properties檔案裡的屬性了,這樣對於經常需要變動的設定檔來說就顯的很方便了。
如果有多個.properties檔案,則可以透過  locations   屬性來設定,
<property name="locations">
<list>
<value>classpath:mailsender1.properties</value>     <value>classpath:mailsender2.properties</value>
</list>
</property>


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.