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>