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


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

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

#郵件發送的相關配置  
email.host = smtp.163.com  
email.port = xxx  
email.username = xxx  
email.password = xxx  
email.sendFrom = xxx@163.com  

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

<!-- spring的屬性加載器,加載properties文件中的屬性 -->  
<bean id="propertyConfigurer"  
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
    <property name="location">  
        <value>application.properties</value>  
    </property>  
    <property name="fileEncoding" value="utf-8" />  
</bean>  

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

<!-- 郵件發送 -->  
    <bean id="mailSender"  
        class="org.springframework.mail.javamail.JavaMailSenderImpl">  
        <property name="host">  
            <value>${email.host}</value>  
        </property>  
        <property name="port">  
            <value>${email.port}</value>  
        </property>  
        <property name="username">  
            <value>${email.username}</value>  
        </property>  
        <property name="password">  
            <value>${email.password}</value>  
        </property>  
        <property name="javaMailProperties">  
            <props>  
                <prop key="mail.smtp.auth">true</prop>  
                <prop key="sendFrom">${email.sendFrom}</prop>  
            </props>  
        </property>  
    </bean>  

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

#生成文件的保存路徑  
file.savePath = D:/test/  
#生成文件的備份路徑,使用后將對應文件移到該目錄  
file.backupPath = D:/test bak/  

  ConfigInfo.java 中對應代碼: 

@Component("configInfo")  
public class ConfigInfo {  
    @Value("${file.savePath}")  
    private String fileSavePath;  
  
    @Value("${file.backupPath}")  
    private String fileBakPath;  
          
    public String getFileSavePath() {  
        return fileSavePath;  
    }  
  
    public String getFileBakPath() {  
        return fileBakPath;  
    }      
}  

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

@Autowired  
private ConfigInfo configInfo;  

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

<context:component-scan base-package="com.my.model" />  

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

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


免責聲明!

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



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