Spring獲取properties文件中的屬性


1.前言

本文主要是對這兩篇blog的整理,感謝作者的分享 
Spring使用程序方式讀取properties文件 
Spring通過@Value注解注入屬性的幾種方式

2.配置文件

application.properties

socket.time.out=1000

 

3.使用spring代碼直接載入配置文件,獲取屬性信息

代碼如下:

Resource resource = new ClassPathResource("/application.properties"); Properties props = PropertiesLoaderUtils.loadProperties(resource);

 

4.使用@Value注解獲取屬性

4.1 使用PropertyPlaceholderConfigurer

spring配置

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:application.properties" /> </bean>

 

代碼

@Value("${socket.time.out}") int socketTimeout;

 

4.2 使用PropertiesFactoryBean

Spring配置

<bean id="application" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> <property name="location" value="classpath:application.properties" /> </bean>

 

代碼

@Value("#{$application['socket.time.out']}") int socketTimeOut;

 

4.3 備注:

如果將代碼部署到resin容器,使用4.1的方法,在程序啟動時,總是報無法將”${socket.time.out}”轉換成整數的錯誤。這說明程序並沒有找到對應的配置屬性。但是在進行單元測試的使用使用ApplicationContext時,則能夠找到對應的屬性。這可能是在容器里面使用的是WebApplicationContext的問題吧。目前還沒有找到確切的原因,現在這里mark一下。 
使用4.2的方式,部署之后能夠獲取對應的屬性值。

 

 

https://blog.csdn.net/wlfighter/article/details/52563605

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM