There is a propertyplaceholderconfigurer class in spring that can be used to replace the variable definitions used in the spring configuration file with ${} in a properties file. For example, sometimes we need to put the configuration information on the NC library in another properties file.
1. First create a Java Bean
Package test; Import Org.apache.commons.lang.builder.ToStringBuilder; public class Mybean {private string name; private string Prop1, private string prop2; private string prop3; public string GetName () {return name.} public void SetName (string name) {this.name = name.} public String GetProp1 () {return PROP1 ; SETPROP1 (String prop1) {THIS.PROP1 = Prop1} public string GetProp2 () {return prop2;} public void Setpro P2 (string prop2) {this.prop2 = PROP2;} public String getProp3 () {return prop3;} public void SetProp3 (String prop3) {T HIS.PROP3 = PROP3; @Override public String toString () {return tostringbuilder.reflectiontostring (this);}}
2. Create spring.xml files
<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" 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-2.0.xsd "default-lazy-init=" true "> <bean id=" Propertyconfigurer "class=" Org.springframework.beans.factory.config.PropertyPlaceholderConfigurer "> < Property Name= "Locations" > <value>classpath:test/spring.properties</value> </property> < Property name= "Systempropertiesmode" > <value>1</value> </property> <property name= " Searchsystemenvironment "> <value>true</value> </property> <property name=" Ignoreunresolvableplaceholders "> <value>true</value> </property> </bean> <bean id=" Mybean "class=" test. Mybean "> <property name=" name "><value>${name}</value></property> <property name="Prop1" ><value>${prop1}</value></property> <property name= "Prop2" ><value>${ prop2}</value></property> <property name= "PROP3" ><value>${prop3}</value></ Property> </bean> </beans>
Use ${NAME},${PROPX} in the configuration file to indicate that you need to replace the content in the properties file
3. Create spring.properties file where variables can recursively refer to other variables defined in the current properties file
Name=kongxx prop1=111 prop2=${prop1}222 prop3=${prop2}333
4. Write a test procedure
Package test; Import Org.springframework.context.ApplicationContext; Import Org.springframework.context.support.ClassPathXmlApplicationContext; public class Test {public static void main (string[] args) {ApplicationContext ctx = new Classpathxmlapplicationcontext ( "/test/spring.xml"); Mybean Mybean = (Mybean) ctx.getbean ("Mybean"); System.out.println (Mybean); } }
Run the test program, the output is as follows:
Test. MYBEAN@1649B44[NAME=KONGXX,PROP1=111,PROP2=111222,PROP3=111222333]