Spring gets the properties in the property file

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.