Spring-bean configuration-Use external properties file
Therefore, you can get the key-value of the configuration file by @value annotations and generate a profile bean. The way to use beans directly in your code.
• 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.). 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 part of the bean configuration out of the properties file. You can use variables of the form ${var} in the bean configuration file. Propertyplaceholderconfigurer a dependency file, and use these properties to replace the variable. spring also allows you to use ${propname} in a property file to enable mutual references between properties. 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:
[Plain]View PlainCopy
- User=scott
- Password=tiger
- Dirverclass=oracle.jdbc.driver.oracledriver
- Jdbcurl=jdbc\:oracle\:thin\: @localhost \:1521\:oracl
Beans configuration file: Applicationcontext_properties.xml
[HTML]View PlainCopy
- <? 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">
- <!--using properties of external properties files--
- < name="user" value="${user}"> </Property>
- < name= "password" value="${password}"> </Property>
- <property name= "driverclass" value="${dirverclass}"></ Property>
- < name= "jdbcurl" value="${jdbcurl}"> </Property>
- </Bean>
- </Beans>
Create the data source code as follows:
[Java]View PlainCopy
- ApplicationContext axt = new Classpathxmlapplicationcontext ("Applicationcontext_properties.xml");
- DataSource DataSource = (DataSource) axt.getbean ("DataSource");
- System.out.println (Datasource.getconnection ());
Spring-bean configuration-Use external properties file (GO)