• When configuring beans in a configuration file, it is sometimes necessary to mix the details of the system deployment in the bean's configuration (for example: file path, data source configuration information, etc.). And these deployment details actually need to be separated from the bean configuration
The Spring provides a propertyplaceholderconfigurer Beanfactory post processor that allows the user to move part of the bean configuration out of the properties file. Can be used in the bean configuration file in the form of ${var} variables, propertyplaceholderconfigurer dependent files, and use these properties to replace the variables.
Spring also allows the use of ${propname} in a property file to implement mutual references between attributes.
case: Use Db.properties to configure the connection database information, obtain the information through the bean configuration file, and then establish the data source;The Db.properties configuration information is as follows:
User=scott
password=tiger
dirverclass=oracle.jdbc.driver.oracledriver
jdbcurl=jdbc\:oracle\:thin\: @localhost \:1521\:oracl
Beans configuration file: Applicationcontext_properties.xml
<?xml version= "1.0" encoding= "UTF-8"?> <beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:
Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:context= "Http://www.springframework.org/schema/context" xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans.xsd Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/ Spring-context-4.0.xsd "> <!--Import Properties file--<context:property-placeholder location=" classpath: Db.properties "/> <bean id=" DataSource "class=" Com.mchange.v2.c3p0.ComboPooledDataSource "> <!-- Use properties of external properties file--<property name= "user" value= "${user}" ></property> <property name= "password" value= " ${password} "></property> <property name=" Driverclass "value=" ${dirverclass} "></property> < Property Name= "Jdbcurl" value= "${jdbcurl}" ></property> </bean> </beans>
Create the data source code as follows:
ApplicationContext axt = new Classpathxmlapplicationcontext ("Applicationcontext_properties.xml");
DataSource DataSource = (DataSource) axt.getbean ("DataSource");
System.out.println (Datasource.getconnection ());