spring_DBCP数据库连接池_DataSource配置创建获取

时间:2022-10-02 04:38:26
package com.bjsxt.dao.impl;

import java.sql.Connection;
import java.sql.SQLException;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.springframework.stereotype.Component;

import com.bjsxt.dao.UserDao;
import com.bjsxt.model.User;

@Component("userDaoImpl")
public class UserDaoImpl implements UserDao {
private DataSource dataSource;

public DataSource getDataSource() {
return dataSource;
}

@Resource(name = "myDataSource")
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}

@Override
public void save(User user) {
try {
Connection cnn = dataSource.getConnection();
cnn.createStatement().executeUpdate(
"insert into user values (null,'zhangsan')");
System.out.println("a save");

} catch (SQLException e) {
e.printStackTrace();
}
}

}


<?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"
xmlns:aop="http://www.springframework.org/schema/aop"
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
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">

<context:annotation-config />
<!-- 自动扫描初始化对象 -->
<context:component-scan base-package="com.bjsxt" />
<!-- 配置数据源DataSource -->
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<!-- results in a setDriverClassName(String) call -->
<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="root" />
</bean>

<!-- 初始化该切面类 -->
<bean id="logInterceptor" class="com.bjsxt.aop.LogInterceptor"></bean>
<aop:config>
<!-- 全局切面逻辑范围 -->
<aop:pointcut expression="execution(public * com.bjsxt.dao..*.save(..))"
id="daoPointcut" />
<!-- 声明一个切面对象 -->
<aop:aspect id="logAspect" ref="logInterceptor">
<!-- 在方法执行之前要执行哪个方法 -->
<aop:before method="brefore" pointcut-ref="daoPointcut" />
</aop:aspect>
</aop:config>
</beans>