Spring框架DataSource
一 DataSource 简易介绍
JDK里 javax.sql的一个接口
public interface DataSource 表示无力数据源的连接,作为DriverManager设施的替代项,
目前通过DataSource对象的getConnection() ,getConnection(String username,String password) 方法是获取连接的首选方法。
Spring 注入Datasource
一、通过XML写入bean
<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="root"/>
</bean>
二、在数据库实现里注入这个bean
这里利用了annotation的方式@resource获取Datasource的bean
注意
1 Datasource引入javax.sql.DataSource;
2 引入common.dbcp , common.pool , JDBC 的JAR包
package com.daoImpl;
import java.sql.SQLException; import javax.annotation.Resource;
import javax.sql.DataSource; import org.springframework.stereotype.Component; import com.dao.UserDao;
import com.entity.User;
@Component
public class UserDaoImpl implements UserDao{
DataSource dataSource ;//import javax.sql, common.dbcp common.pool jdbc public void save(User user) {
try {
java.sql.Connection con = dataSource.getConnection();
con.createStatement().execute("insert into test value('1','aa')");
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(user.getName()+"-->"+user.getRemark()+" save --调用UserDaoImpl!");
} public void update(User user) {
System.out.println(user.getName()+"-->"+user.getRemark()+" update --调用UserDaoImpl!");
} public DataSource getDataSource() {
return dataSource;
}
@Resource
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
}
测试类
package com.serviceImpl.test;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext; import com.entity.User;
import com.serviceImpl.UserServiceImpl; public class UserServiceImplTest {
User user; @Before
public void setUp() throws Exception {
user = new User();
user.setName("testName");
user.setRemark("testRemark");
} @Test
public void testAdd() {
ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("beans.xml");
UserServiceImpl UserServiceImpl = (UserServiceImpl)app.getBean("userServiceImpl");
UserServiceImpl.add(user);//调用方法
UserServiceImpl.update(user);//调用方法
}
}
执行结果

三、DBCP的另外三个属性介绍
MaxIdle:最大的空闲连接数。如果超过数据库连接的最大空闲时间,数据库连接将被标记为不可用,然后被释放。设为0表示无限制;设置为20,表示即使没有数据库连接请求时,依然可以保持20空闲的连接,而不被清除,随时处于待命状态。
MaxActive:连接池的最大数据库连接数。设为0表示无限制;设置为20,表示同时最多有20个数据库连接。一般把maxActive设置成可能的并发量就行了。
MaxWait:数据库连接请求的最大等待时间,单位ms。如果超过此时间将得到一个异常。设为-1表示无限制。
BasicDataSource 相关的参数说明:
defaultAutoCommit:对于事务是否 autoCommit, 默认值为 true
defaultReadOnly:对于数据库是否只能读取, 默认值为 false
removeAbandoned:是否自我中断, 默认是 false
removeAbandonedTimeout:几秒后会自我中断, removeAbandoned 必须为 true
logAbandoned:是否记录中断事件, 默认为 false
四、使用占位符+property配置注入XML的bean能取得一样的效果
关键代码
<bean id="mappings"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<value>classpath:jdbc.properties</value>
</property>
</bean> <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>
jdbc.properties 配置
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring
jdbc.username=root
jdbc.password=root
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:aop="http://www.springframework.org/schema/aop"
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
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd"> <context:annotation-config/>
<context:component-scan base-package="com"></context:component-scan>
<aop:config>
<aop:aspect id="logInterceptor" ref="logInterceptor">
<aop:pointcut expression="execution(public void com.daoImpl.UserDaoImpl.*(..))" id="myAop" />
<aop:before pointcut-ref="myAop" method="beforMethod" /><aop:after pointcut-ref="myAop" method="afterMethod" />
<aop:around pointcut-ref="myAop" method="around"/>
</aop:aspect>
</aop:config> <bean id="mappings"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<value>classpath:jdbc.properties</value>
</property>
</bean> <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> <!-- <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="root"/>-->
<!-- </bean>--> </beans>
执行结果和之前一致
总结
1 spring 通过配置XML datasource的bean
推荐用 jdbc.properties 配置,方便管理,引入PropertyPlaceholderConfigurer即可
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations">
<value>classpath:jdbc.properties</value>
</property>
2 把bean注入到datasource实现类的setter方法上 注意Datasource引用的是java.sql
3 引入所需要的JAR包,dbcp,pool,jdbc
4 完成
Spring框架DataSource的更多相关文章
- Spring框架学习(一)
一. spring概述 Spring 框架是一个分层架构,由 7 个定义良好的模块组成.Spring 模块构建在核心容器之上,核心容器定义了创建.配置和管理 bean 的方式,如图 1 所示. 图 1 ...
- 使用 Spring Boot 快速构建 Spring 框架应用--转
原文地址:https://www.ibm.com/developerworks/cn/java/j-lo-spring-boot/ Spring 框架对于很多 Java 开发人员来说都不陌生.自从 2 ...
- 【Spring】浅析Spring框架的搭建
c目录结构: // contents structure [-] Spring是什么 搭建Spring框架 简单Demo 1,建立User类 2,建立Test类 3,建立ApplicationCont ...
- Spring框架的XML扩展特性
Spring框架从2.0版本开始,提供了基于Schema风格的XML扩展机制,允许开发者扩展spring配置文件.现在我们来看下怎么实现这个功能,可以参考spring帮助文档中的<Extensi ...
- spring框架面试相关问题
Spring 框架中核心组件有三个:Core.Context 和 Beans.其中最核心的组件就是Beans, Spring提供的最核心的功能就是Bean Factory. Spring 解决了的最核 ...
- 深入剖析 Spring 框架的 BeanFactory
说到Spring框架,人们往往大谈特谈一些似乎高逼格的东西,比如依赖注入,控制反转,面向切面等等.但是却忘记了最基本的一点,Spring的本质是一个bean工厂(beanFactory)或者说bean ...
- 再析在spring框架中解决多数据源的问题
在前面我写了<如何在spring框架中解决多数据源的问题>,通过设计模式中的Decorator模式在spring框架中解决多数据源的问题,得到了许多网友的关注.在与网友探讨该问题的过程中, ...
- 如何在spring框架中解决多数据源的问题
在我们的项目中遇到这样一个问题:我们的项目需要连接多个数据库,而且不同的客户在每次访问中根据需要会去访问不同的数据库.我们以往在spring和hibernate框架中总是配置一个数据源,因而sessi ...
- 。。。Spring框架总结(一)。。。
Spring框架已经学习了两遍了,第一遍基本上忘得差不多了,现在开始复习第二遍的,也复习的差不多了,比之前懂了很多东西,今天就写下来,记录一下我滴小成果! 首先,在Spring框架中有两个重要的概念: ...
随机推荐
- RTMP,RTMPT,RTMPS,RTMPE,RTMPTE协议的介绍
1. AMF AMF(是Action Message Format的缩写)是在flash和flex中与远程服务端交换数据的一种格式.它是二进制格式,Flash应用与服务端或数据库通过RPC交换数据时, ...
- PHP:php遍历数组each()方法总结
each()的作用是将数组当前元素的键值对拆成一个新数组,并把下一个元素作为当前元素.比如Array(...,'Robert'=>'Bob',...)中的'Robert'=>'Bob'键值 ...
- log4j.properties中的这句话“log4j.logger.org.hibernate.SQL=DEBUG ”该怎么写在log4j.xml里面呢?
http://www.cnblogs.com/gredswsh/p/log4j_xml_properties.html 请问:log4j.properties中的这句话“log4j.logger.or ...
- Using Autorelease Pool Blocks
https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmAut ...
- MooseFS 3.0 集群环境部署过程
1 准备好6台虚拟机:(centos7) Master server: 192.168.242.135 Cgi server: 192.168.242.135 meta ...
- window下部署yapi
YApi 是一个可本地部署的.打通前后端及QA的.可视化的接口管理平台. 环境要求 nodejs(尽量最新版本) mongodb(尽量最新版本) 1.安装node https://www.runoob ...
- 零基础快速入门SpringBoot2.0教程 (四)
一.JMS介绍和使用场景及基础编程模型 简介:讲解什么是小写队列,JMS的基础知识和使用场景 1.什么是JMS: Java消息服务(Java Message Service),Java平台中关于面向消 ...
- Vim编辑器基础命令
Linux系统中都默认安装了vi或vim编辑器,两种命令基本一致.vim为Vi IMproved,功能更强大. vim有命令模式,输入模式,和末行模式三种. ➢ 命令模式:控制光标移动,可对文本进行复 ...
- Vmware 不能上网
Vmware 安装 WIN7 不能上网,如何解决? 情况一: 虚拟机右下角出现红色叉号,检查物理的服务是否开启“VMware NAT Service” 1 .开启方法:WIN + R -> 输入 ...
- leetcode笔记(一)309. Best Time to Buy and Sell Stock with Cooldown
题目描述 (原题目链接) Say you have an array for which the ith element is the price of a given stock on day i. ...