1. 程式人生 > >Spring獲取properties文件中的屬性

Spring獲取properties文件中的屬性

https lac 整理 rop spring配置 bar BE adp snippet

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

Spring獲取properties文件中的屬性