1. Preface
This article is mainly the collation of the two blog, thanks to the author's sharing
Spring uses program mode to read the properties file
Several ways spring uses @value annotations to inject properties
2. Configuration files
Application.properties
socket.time.out=1000
3. Load the configuration file directly with the spring code to get the property information
The code is as follows:
new ClassPathResource("/application.properties");Properties props = PropertiesLoaderUtils.loadProperties(resource);
4. Using @value annotations to get Properties 4.1 using 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 Notes:
If you deploy code to the resin container, use the 4.1 method, and always report that "${socket.time.out}" cannot be converted to an integer error when the program starts. This indicates that the program did not find the corresponding configuration property. However, when you use ApplicationContext for unit testing, you can find the corresponding property. This may be a problem with webapplicationcontext in the container. There are no exact reasons for this, so mark here.
Using the 4.2 approach, the corresponding property values can be obtained after deployment.
52563605
Spring gets the properties in the property file