Spring提供数据库连接池:DBCP配置DataSource并且获取连接完成数据库操作:
Spring帮助文档的地址:
[http://static.springsource.org/spring/docs/2.5.6/reference/beans.html#beans-value-element](http://static.springsource.org/spring/docs/2.5.6/reference/beans.html#beans-value-element)
以下内容需要导入的jar包:
commons-dbcp.jar
commons-pool.jar
mysql-connector-java-5.0-nightly-20071116-bin.jar
**1. 首先在容器内配置数据源**
~~~
<!-- 配置数据源 -->
<bean id="myDataSource" 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/sms"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
~~~
**2.拿到注入数据源并且编写对数据库的操作**
~~~
@Component("userService")
public class UserServiceImpl implements UserService{
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Resource //resource注入
private DataSource myDataSource;
public DataSource getMyDataSource() {
return myDataSource;
}
public void setMyDataSource(DataSource myDataSource) {
this.myDataSource = myDataSource;
}
//在下面方法前面加逻辑
public void save(){
try{
//拿到连接执行操作
Connection conn = myDataSource.getConnection();
conn.createStatement().execute("insert into dept values('6','bumen2')");
}catch(Exception e){
e.printStackTrace();
}
}
}
~~~
**3.测试运行**
~~~
@Test
public void test01() {
BeanFactory applicationContext = new ClassPathXmlApplicationContext(
"beans.xml");
UserService user = (UserService) applicationContext.getBean("userService");
user.save();
}
~~~
**-通过Properties的方式配置xml的datasource:**
**1、 编写properties文件:**
~~~
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/sms
jdbc.username=root
jdbc.password=root
~~~
**2、编写xml容器配置:**
~~~
<!-- placeholder 占位符 -->
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<value>classpath:jdbc.properties</value>
</property>
</bean>
<bean id="dataSource" destroy-method="close"
class="org.apache.commons.dbcp.BasicDataSource">
<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>
~~~
- 前言
- 一、Ioc控制反转注入原理
- 二、Ioc控制反转集合注入和Scope
- 三、Bean的懒加载和生命周期
- 四、基于Annotation的bean
- 五、Spring容器组建注解@Component和Resouces实现完全注解配置
- 六、Spring自动装配注解@Autowired
- 七、Spring Aop的理解和简单实现
- 八、Spring Aop织入点语法和相关案例总结
- 九、Spring Aop 用xml的方式实现
- 十、Spring DBCP用xml和properties2种格式配置DataSource
- 十一、Spring整合Hibernte
- 十二、Spring中Annotation声明事务
- 十三、Spring中Xml声明事务
- 十四、Spring中hibernateTemplate的使用