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;
Spring provides a propertyplaceholderconfigurer Beanfactory post processor that allows the user to move the contents of the bean configuration to a property file, which can be used in the bean configuration file in the form of ${var} variables, propertyplaceholderconfigurer dependent files, and use these attributes to replace attribute variables;
Spring also allows the use of ${propname} in property files to implement mutual references between attributes.
Example:
1. Import the jar package for the C3P0 data source and the driver jar package for MySQL;
2. Writing Beans-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" > <!-- &nbsP; <property name= "User" value= "root" ></property> <property name= "Password" value= "root" ></property> <property name= "Driverclass" value= "Com.mysql.jdbc.Driver" ></ Property> <property name= "JdbcUrl" value= "JDBC: Mysql:///test "></property> --> <!-- Using properties of an extern properties file --> <property name= "User" value= "${user}" ></property> <property name= "Password" value= "${password}" ></property> <property name= "Driverclass" value= "${driverclass}" ></ property> &Nbsp; <property name= "Jdbcurl" value= "${jdbcurl}" ></property > </bean></beans>
3. Writing the external properties file db.properties
User=rootpassword=rootdriverclass=com.mysql.jdbc.driverjdbcurl=jdbc:mysql:///test
4. Writing Main.java
Package Com.ksk.spring.beans.scope;import Java.sql.sqlexception;import Javax.sql.datasource;import Org.springframework.context.applicationcontext;import Org.springframework.context.support.classpathxmlapplicationcontext;import Com.ksk.spring.car;public class Main {PU Blic static void Main (string[] args) throws SQLException {ApplicationContext ctx = new Classpathxmlapplicationcont Ext ("Beans-properties.xml"); DataSource DataSource = (DataSource) ctx.getbean ("DataSource"); System.out.println (Datasource.getconnection ()); }}
Spring4 Learning: Using external properties files