詳解利用Spring加載Properties配置文件。本站提示廣大學習愛好者:(詳解利用Spring加載Properties配置文件)文章只能為提供參考,不一定能成為您想要的結果。以下是詳解利用Spring加載Properties配置文件正文
記得之前寫Web項目的時候配置文件的讀取都是用Properties這個類完成的,當時為了項目的代碼的統一也就沒做什麼改動。但事後一直在琢磨SpringMVC會不會都配置的注解功能了?經過最近的研究返現SpringMVC確實帶有這一項功能,Spring確實很強大。
因為代碼很簡單,我就貼上我測試的代碼,按照步驟做就可以實現了。
新建配置文件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'會調入到對應的配置文件中,這樣也可以驗證我們的配置是否生效。
現在雖然知道如何使用注解加載配置文件了,但是PropertiesFactoryBean和PreferencesPlaceholderConfigurer的區別和作用還沒有弄清楚,另外Spring的單元測試框架也沒有怎麼研究,如果知道的讀者可以再下方留言告述我,如果沒人回答的話只能以後有時間慢慢研究了。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持。