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/
@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做相應的添加修改。