Detail loading the Properties configuration file using Spring

  • 2020-06-23 00:26:50
  • OfStack

Remember that when I wrote the Web project, I used Properties to read the configuration files, and nothing was changed for the project code. But after 1 wonder SpringMVC will be configured to annotate the function? Recent studies have shown that SpringMVC does have this capability, and Spring is very powerful.

Since the code is simple, I just post the code I'm testing and follow the steps to implement it.

New configuration file jdbc.properties


username=root
password=root

Create and configure spring-ES18en


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

 <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
   <property name="locations">
     <list>
       <value>classpath:jdbc.properties</value>
     </list>
   </property>
   <property name="fileEncoding" value="UTF-8"/>
 </bean>
 <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
   <property name="properties" ref="configProperties"/>
 </bean>
</beans>

New unit test


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/spring-properties.xml")
public class TestTrans {
 @Value("#{configProperties['username']}")
 private String username;
 @Value("#{configProperties['password']}")
 private String password;
 @Test
 public void testProperties(){
   System.out.println("---");
   System.out.println(username);
   System.out.println(password);
 }
}

If you annotate Properties in this way, Intelij IDEA will be prompted. Holding down Ctrl and clicking on the property 'username' will bring it into the corresponding configuration file, which will also verify that our configuration is valid.

Now I know how to use annotations to load configuration files, but the differences and functions between PropertiesFactoryBean and PreferencesPlaceholderConfigurer have not been clarified, and the unit testing framework of Spring has not been studied very much. If you know, please let me know in the comments below. If no one answers, I will only have time to study it later.


Related articles: