詳解利用Spring加載Properties配置文件

記得之前寫Web項目的時候配置文件的讀取都是用Properties這個類完成的,當時為了項目的代碼的統(tǒng)一也就沒做什么改動。但事后一直在琢磨SpringMVC會不會都配置的注解功能了?經(jīng)過最近的研究返現(xiàn)SpringMVC確實帶有這一項功能,Spring確實很強大。

創(chuàng)新互聯(lián)是專業(yè)的贛州網(wǎng)站建設(shè)公司,贛州接單;提供成都網(wǎng)站設(shè)計、成都網(wǎng)站制作,網(wǎng)頁設(shè)計,網(wǎng)站設(shè)計,建網(wǎng)站,PHP網(wǎng)站建設(shè)等專業(yè)做網(wǎng)站服務(wù);采用PHP框架,可快速的進行贛州網(wǎng)站開發(fā)網(wǎng)頁制作和功能擴展;專業(yè)做搜索引擎喜愛的網(wǎng)站,專業(yè)的做網(wǎng)站團隊,希望更多企業(yè)前來合作!

因為代碼很簡單,我就貼上我測試的代碼,按照步驟做就可以實現(xiàn)了。

新建配置文件jdbc.properties

username=root
password=root

新建并配置文件spring-properties

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

 <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
   <property name="locations">
     <list>
       <value>classpath:jdbc.properties</value>
     </list>
   </property>
   <property name="fileEncoding" value="UTF-8"/>
 </bean>
 <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
   <property name="properties" ref="configProperties"/>
 </bean>
</beans>

新建單元測試

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/spring-properties.xml")
public class TestTrans {
 @Value("#{configProperties['username']}")
 private String username;
 @Value("#{configProperties['password']}")
 private String password;
 @Test
 public void testProperties(){
   System.out.println("---");
   System.out.println(username);
   System.out.println(password);
 }
}

使用上面這種方式注解Properties的話Intelij IDEA會有提示的,按住Ctrl然后將鼠標點擊屬性'username'會調(diào)入到對應(yīng)的配置文件中,這樣也可以驗證我們的配置是否生效。

現(xiàn)在雖然知道如何使用注解加載配置文件了,但是PropertiesFactoryBean和PreferencesPlaceholderConfigurer的區(qū)別和作用還沒有弄清楚,另外Spring的單元測試框架也沒有怎么研究,如果知道的讀者可以再下方留言告述我,如果沒人回答的話只能以后有時間慢慢研究了。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。

分享標題:詳解利用Spring加載Properties配置文件
分享URL:http://muchs.cn/article32/gdcepc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供定制開發(fā)、用戶體驗虛擬主機、定制網(wǎng)站、動態(tài)網(wǎng)站、響應(yīng)式網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

搜索引擎優(yōu)化