Spring get properties in properties file

1 Introduction

This article is mainly to organize these two blogs. Thanks to the author for sharing  several ways
that Spring uses programmatically to read properties file  
Spring injects properties through @Value annotation

2. Configuration file

application.properties

socket.time.out=1000

 

3. Use spring code to directly load the configuration file to obtain attribute information

code show as below:

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

 

4. Use the @Value annotation to get properties

4.1 使用PropertyPlaceholderConfigurer

spring configuration

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

 

code

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

 

4.2 Using PropertiesFactoryBean

Spring configuration

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

 

code

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

 

4.3 Remarks:

If you deploy the code to the resin container and use the method of 4.1, the error that "${socket.time.out}" cannot be converted to an integer is always reported when the program starts. This means that the program did not find the corresponding configuration property. However, when using ApplicationContext for unit testing, you can find the corresponding properties. This may be the problem of using WebApplicationContext in the container. The exact reason has not been found yet, so mark it here now. 
Using the method of 4.2, the corresponding attribute value can be obtained after deployment.

 

 

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

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325375331&siteId=291194637