一. 回顾
前面Day15——配置C3P0连接池讲到使用XML文件配置C3P0连接池。今天讲一下将XML文件里面的配置信息提取到外部文件中,再在XML文件里面引用那个外部文件去配置连接池。
本文章的项目源码已上传到本博客的“资源”处,可前往免费下载
二. 储备知识
当Bean的配置信息主键增多时,查找和修改一些bean的配置信息就变得愈加困难。==这时可以将一部分的配置信息提取到bean配置文件的外部,以properties格式的属性文件保存起来,同时在bean配置文件中引用properties属性文件中的内容。==从而实现一部分属性值发生变化时仅需修改properties属性文件即可。这种技术多用于连接数据库的基本信息的配置。
三. 例子
db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/onlinebookshop
jdbc.user=root
jdbc.password=123456
jdbc.initPoolSize=5
jdbc.maxPoolSize=20
spring-dbProperties.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">
<!-- 第一种引用方式 -->
<!-- <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:db.properties"></property>
</bean> -->
<!-- 第二种方式 -->
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="initialPoolSize" value="${jdbc.initPoolSize}"></property>
<property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
</bean>
</beans>
Main.java
package com.atguigu.spring.dbProperties;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
ApplicationContext context =
new ClassPathXmlApplicationContext("spring-dbProperties.xml");
DataSource ds = context.getBean("dataSource", DataSource.class);
System.out.println(ds);
System.out.println(ds.getConnection());
}
}