Spring DBCP 数据库连接池配置

Spring dbcp 数据库连接池的配置

DataSource的配置与使用
第一步:引入相关的jar包
  • commons-dbcp-1.4.jar
  • commons-pool-1.6.jar

[b]在beans.xml里面对DataSource进行配置[/b]
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
	destroy-method="close">
	<property name="driverClassName" value="com.mysql.jdbc.Driver" />
	<property name="url" value="jdbc:mysql://localhost:3306/spring" />
	<property name="username" value="root" />
	<property name="password" value="***" />
</bean>

使用DataSource创建链接并对数据进行操作
public class UserDAOImpl implements UserDAO {

	@Resource        //DI  Dependency Injection
	private DataSource dataSource;

	public void save(User user) {
		try {
			Connection conn = dataSource.getConnection();
			conn.createStatement().executeUpdate("insert into user values (null , 'roy')");
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		System.out.println("user saved!");
	}

	public DataSource getDataSource() {
		return dataSource;
	}

	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}
}

使用点位符进行配置:
在beans.xml配置如下
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
	destroy-method="close">
	<property name="driverClassName" value="${jdbc.driverClassName}" />
	<property name="url" value="${jdbc.url}" />
	<property name="username" value="${jdbc.username}" />
	<property name="password" value="${jdbc.password}" />
</bean>
<context:property-placeholder location="jdbc.properties" />

在src目录下面添文件jdbc.properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring
jdbc.username=root
jdbc.password=****

你可能感兴趣的:(spring,mysql,DBCP,configuration)