Spring 中使用Properties檔案,springproperties

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.