Spring 配置数据源
1. 1数据源(连接池)的作用
- 连接池(数据源)是提高程序性能出现的
- 事先实例化数据源,初始化部分连接资源
- 使用连接资源时从数据源中获取
- 连接完毕后将连接资源归还给数据源
常见数据源(连接池): DBCP,C3P0,BoneCP,Druid等....
1.2 数据源的开发步骤
- 导入数据源的坐标和数据库驱动坐标
- 创建数据源对象
- 设置数据源的基本连接数据(驱动,地址,用户名,密码..........)
- 使用数据源获取连接资源和归还连接资源
1.3 Spring配置数据源 (c3p0为例)
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.cj.jdbc.Driver"/>
<property name="user" value="root"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost/spring"/>
<property name="password" value="password"/>
</bean>
Druid等类似........
1.4 抽取jdbc配置文件
applicationContext.xml加载jdbc.properties配置文件获得连接信息
首先,需要引入Context命名空间和约束路径:
- 命名空间:
xmlns:context="http://www.springframework.org/schema/context" - 约束路径:
http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd
<?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.xsd">
<!-- 加载外部properties文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="user" value="${jdbc.username}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
</beans>