欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時(shí)間:2017年04月17日 10:59:43   作者:陳的簡(jiǎn)書(shū)  
本篇文章主要介紹了詳解利用Spring加載Properties配置文件,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧

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

因?yàn)榇a很簡(jiǎn)單,我就貼上我測(cè)試的代碼,按照步驟做就可以實(shí)現(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>

新建單元測(cè)試

@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會(huì)有提示的,按住Ctrl然后將鼠標(biāo)點(diǎn)擊屬性'username'會(huì)調(diào)入到對(duì)應(yīng)的配置文件中,這樣也可以驗(yàn)證我們的配置是否生效。

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

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論