Spring 中使用Properties檔案,springproperties
Spring提供了載入Properties檔案的工具類:org.springframework.beans.factory.config.PropertyPlaceholderConfigurer。
在Spring容器啟動時,使用內建bean對屬性檔案資訊進行載入,在bean.xml中添加如下:
<!-- spring的屬性載入器,載入properties檔案中的屬性 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location"> <value>/WEB-INF/configInfo.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對象:@Autowiredprivate ConfigInfo configInfo;需在bean.xml中添加組件掃描器,用於註解方式的自動注入:<context:component-scan base-package="com.my.model" />(上述包model中包含了ConfigInfo類)。通過get方法擷取對應的屬性資訊,優點是代碼中使用方便,缺點是如果代碼中需用到新的屬性資訊,需對ConfigInfo.java做相應的添加修改。