一 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的更多相关文章

  1. Spring框架学习(一)

    一. spring概述 Spring 框架是一个分层架构,由 7 个定义良好的模块组成.Spring 模块构建在核心容器之上,核心容器定义了创建.配置和管理 bean 的方式,如图 1 所示. 图 1 ...

  2. 使用 Spring Boot 快速构建 Spring 框架应用--转

    原文地址:https://www.ibm.com/developerworks/cn/java/j-lo-spring-boot/ Spring 框架对于很多 Java 开发人员来说都不陌生.自从 2 ...

  3. 【Spring】浅析Spring框架的搭建

    c目录结构: // contents structure [-] Spring是什么 搭建Spring框架 简单Demo 1,建立User类 2,建立Test类 3,建立ApplicationCont ...

  4. Spring框架的XML扩展特性

    Spring框架从2.0版本开始,提供了基于Schema风格的XML扩展机制,允许开发者扩展spring配置文件.现在我们来看下怎么实现这个功能,可以参考spring帮助文档中的<Extensi ...

  5. spring框架面试相关问题

    Spring 框架中核心组件有三个:Core.Context 和 Beans.其中最核心的组件就是Beans, Spring提供的最核心的功能就是Bean Factory. Spring 解决了的最核 ...

  6. 深入剖析 Spring 框架的 BeanFactory

    说到Spring框架,人们往往大谈特谈一些似乎高逼格的东西,比如依赖注入,控制反转,面向切面等等.但是却忘记了最基本的一点,Spring的本质是一个bean工厂(beanFactory)或者说bean ...

  7. 再析在spring框架中解决多数据源的问题

    在前面我写了<如何在spring框架中解决多数据源的问题>,通过设计模式中的Decorator模式在spring框架中解决多数据源的问题,得到了许多网友的关注.在与网友探讨该问题的过程中, ...

  8. 如何在spring框架中解决多数据源的问题

    在我们的项目中遇到这样一个问题:我们的项目需要连接多个数据库,而且不同的客户在每次访问中根据需要会去访问不同的数据库.我们以往在spring和hibernate框架中总是配置一个数据源,因而sessi ...

  9. 。。。Spring框架总结(一)。。。

    Spring框架已经学习了两遍了,第一遍基本上忘得差不多了,现在开始复习第二遍的,也复习的差不多了,比之前懂了很多东西,今天就写下来,记录一下我滴小成果! 首先,在Spring框架中有两个重要的概念: ...

随机推荐

  1. Sentinel spring-cloud-gateway adapter(1.6)异常错误之@EnableCircuitBreaker

    sentinal 大坑 使用gateway adaper包出现@EnableCircuitBreaker did you forget include starter的异常 这时候千万不要学我引入cl ...

  2. JavaScript: apply , call 方法

    我在一开始看到javascript的函数apply和call时,非常的模糊,看也看不懂,最近在网上看到一些文章对apply方法和call的一些示例,总算是看的有点眉目了,在这里我做如下笔记,希望和大家 ...

  3. 64位系统中为VS2012添加OpenGL工具包

    之前一直都是按照网上教程进行的添加,以前使用的系统是32位的,所以一直都没有问题.最近换了64位系统,要使用到OpenGL,于是就又进行了原来的工作,但进行测试时,老是失败: 但是在目录:" ...

  4. IOS ViewTable

    // //  ViewController.swift //  UITableView // //  Created by lanou on 16/11/7. //  Copyright (c) 20 ...

  5. Eclipse 发布 JAR

    明确要生成何种类型 jar 生成工具 jar,作为包被其他程序调用 具体步骤: 选中项目文件,点右键选择 Export ,JAR File 在弹出窗口选择,导出哪些文件,并且选择好 输出 JAR 的路 ...

  6. spring boot 集成swagger2

    1  在pom.xml中加入Swagger2的依赖 <dependency> <groupId>io.springfox</groupId> <artifac ...

  7. PHP array_multisort()函数超详细理解

    项目中用到这个函数了 ,起初对这个函数一直是懵逼状态,文档都看的朦朦胧胧的 网上无意间看到这篇文章 ,写的超级详细,收藏了 . 当然要先放原地址:https://www.cnblogs.com/WuN ...

  8. JZOJ 3223. 【HBOI2013】Ede的新背包问题

    3223. [HBOI2013]Ede的新背包问题 (Standard IO) Time Limits: 2000 ms  Memory Limits: 262144 KB  Detailed Lim ...

  9. 指针的操作 p*++

    int x, y, *px = &x, *py = &y; y = *px + ; //表示把x的内容加5并赋给y,*px+5相当于(*px)+5 y = ++*px; //px的内容 ...

  10. HDU - 1054 Strategic Game (二分图匹配模板题)

    二分图匹配模板题 #include <bits/stdc++.h> #define FOPI freopen("in.txt", "r", stdi ...