一、属性配置文件
dataSource.url=jdbc:mysql://xxx.xxx.xxx.xxx/test
dataSource.username=root
dataSource.password=xxxxxx
dataSource.driverClassName=com.mysql.jdbc.Driver
#dataSource.type=com.alibaba.druid.pool.DruidDataSource
二、spring配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean class="org.springframework.beans.factory.config.PropertyOverrideConfigurer">
<property name="locations" value="classpath:cn/edu/tju/jdbc2.properties"/>
</bean>
<bean id="dataSource"
class="com.alibaba.druid.pool.DruidDataSource">
</bean>
</beans>
三、测试类:
package cn.edu.tju.test;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.sql.SQLException;
public class Test06 {
public static void main(String[] args) throws Exception {
ConfigurableApplicationContext ctx = new
ClassPathXmlApplicationContext("spring6.xml");
DruidDataSource dataSource = ctx.getBean("dataSource", DruidDataSource.class);
DruidPooledConnection connection = dataSource.getConnection();
System.out.println(connection);
}
}
xml文件中配置的属性值会被properties文件中的属性覆盖。
PropertyOverrideConfigurer父类是PropertyResourceConfigurer,它是一个BeanFactoryPostProcessor,所以,它的postProcessBeanFactory会被执行,这个方法代码如下:
这个方法首先获取到了属性值,然后调用processProperties方法(位于PropertyOverrideConfigurer类),这个方法代码如下:
可以看到它遍历Properties,然后调用了processKey方法,processKey的代码如下:
可以看到,调用了applyPropertyValue方法,传入了BeanFactory, BeanName, BeanProperty,value,
applyPropertyValue的代码如下:
可以看到,首先获取到了BeanDefinition,然后包装了一个PropertyValue,最后将包装的PropertyValue设置到了BeanDefinition.