Spring中屬性文件properties的讀取與使用


實際項目中,通常將一些可配置的定制信息放到屬性文件中(如數據庫連接信息,郵件發送配置信息等),便於統一配置管理。例中將需配置的屬性信息放在屬性文件/WEB-INF/configInfo.properties中。 

其中部分配置信息(郵件發送相關): 

Java代碼   收藏代碼
  1. #郵件發送的相關配置  
  2. email.host = smtp.163.com  
  3. email.port = xxx  
  4. email.username = xxx  
  5. email.password = xxx  
  6. email.sendFrom = xxx@163.com  


在Spring容器啟動時,使用內置bean對屬性文件信息進行加載,在bean.xml中添加如下: 

Xml代碼   收藏代碼
  1. <!-- spring的屬性加載器,加載properties文件中的屬性 -->  
  2. <bean id="propertyConfigurer"  
  3.     class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  4.     <property name="location">  
  5.         <value>/WEB-INF/configInfo.properties</value>  
  6.     </property>  
  7.     <property name="fileEncoding" value="utf-8" />  
  8. </bean>  


屬性信息加載后其中一種使用方式是在其它bean定義中直接根據屬性信息的key引用value,如郵件發送器bean的配置如下: 

Xml代碼   收藏代碼
  1. <!-- 郵件發送 -->  
  2.     <bean id="mailSender"  
  3.         class="org.springframework.mail.javamail.JavaMailSenderImpl">  
  4.         <property name="host">  
  5.             <value>${email.host}</value>  
  6.         </property>  
  7.         <property name="port">  
  8.             <value>${email.port}</value>  
  9.         </property>  
  10.         <property name="username">  
  11.             <value>${email.username}</value>  
  12.         </property>  
  13.         <property name="password">  
  14.             <value>${email.password}</value>  
  15.         </property>  
  16.         <property name="javaMailProperties">  
  17.             <props>  
  18.                 <prop key="mail.smtp.auth">true</prop>  
  19.                 <prop key="sendFrom">${email.sendFrom}</prop>  
  20.             </props>  
  21.         </property>  
  22.     </bean>  


另一種使用方式是在代碼中獲取配置的屬性信息,可定義一個javabean:ConfigInfo.java,利用注解將代碼中需要使用的屬性信息注入;如屬性文件中有如下信息需在代碼中獲取使用: 

Java代碼   收藏代碼
  1. #生成文件的保存路徑  
  2. file.savePath = D:/test/  
  3. #生成文件的備份路徑,使用后將對應文件移到該目錄  
  4. file.backupPath = D:/test bak/  


ConfigInfo.java 中對應代碼: 

Java代碼   收藏代碼
  1. @Component("configInfo")  
  2. public class ConfigInfo {  
  3.     @Value("${file.savePath}")  
  4.     private String fileSavePath;  
  5.   
  6.     @Value("${file.backupPath}")  
  7.     private String fileBakPath;  
  8.           
  9.     public String getFileSavePath() {  
  10.         return fileSavePath;  
  11.     }  
  12.   
  13.     public String getFileBakPath() {  
  14.         return fileBakPath;  
  15.     }      
  16. }  


業務類bo中使用注解注入ConfigInfo對象: 

Java代碼   收藏代碼
  1. @Autowired  
  2. private ConfigInfo configInfo;  


需在bean.xml中添加組件掃描器,用於注解方式的自動注入: 

Xml代碼   收藏代碼
  1. <context:component-scan base-package="com.my.model" />  

(上述包model中包含了ConfigInfo類)。 

通過get方法獲取對應的屬性信息,優點是代碼中使用方便,缺點是如果代碼中需用到新的屬性信息,需對ConfigInfo.java做相應的添加修改。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM