Spring-配置数据源

本文详细介绍了Spring中数据源(连接池)的作用,包括DBCP、C3P0、BoneCP、Druid等常见连接池的使用,并通过实例展示了如何配置数据源,以及如何从properties文件中读取配置。在Spring环境中,讲解了如何配置数据源,引入外部properties文件,并处理常见错误。通过示例代码解析,帮助理解Spring管理数据源的过程。
摘要由CSDN通过智能技术生成

Spring学习笔记目录

数据源(连接池)的作用

事先实例化数据源,初始化部分连接资源
使用连接资源时从数据源中获取
使用完毕后将连接资源归还给数据源
常见的数据源(连接池):DBCP、C3P0、BoneCP、Druid等
——黑马程序员

简而言之:先连接,获取数据,归还资源。
使用步骤:

①导入数据源的坐标和数据库驱动坐标
②创建数据源对象
③设置数据源的基本连接数据
④使用数据源获取连接资源和归还连接资源
——黑马程序员

简而言之:
①导入Mean依赖或是包依赖
然后:先连接,获取数据,归还资源。
第③步的设置基本额度参数信息:驱动,数据库地址,用户名,密码。
④关闭连接即可。

项目示例

项目结构:
在这里插入图片描述
导入maven依赖,把一下的依赖复制到项目中的iml文件中导入依赖即可

<dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.32</version>
        </dependency>
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

mysql:导入mysql数据库的jdbc驱动。
c3p0:jdbc数据库连接池。
druid:jdbc数据库连接池。
junit:单元测试框架。
新建类DataSourceTest.java:

package com.test;

import com.alibaba.druid.pool.DruidAbstractDataSource;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.junit.Test;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.util.ResourceBundle;

/**
 * @version:
 * @author: 零乘一
 * @description:
 * @date: 2021/9/25 18:46
 **/
public class DataSourceTest {
    @Test
    //测试手动创建 druid数据源
    public void test2() throws Exception{
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/test");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        DruidPooledConnection connection = dataSource.getConnection();
        System.out.println(connection);
        connection.close();
    }

    @Test
    //测试手动创建c3p0数据源
    public void test1() throws Exception {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();//创建数据源对象
        //设置基本的连接参数
        dataSource.setDriverClass("com.mysql.jdbc.Driver");//设置jdbc
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");//设置数据库地址
        dataSource.setUser("root");//设置账号
        dataSource.setPassword("root");//设置密码
        Connection connection = dataSource.getConnection();//获取资源
        System.out.println(connection);//打印数据源
        connection.close();//关闭资源
    }
}

运行结果

test1:connection的结果被打印出,证明连接成功
在这里插入图片描述
test2:connection的结果被打印出,证明连接成功
在这里插入图片描述

常见错误

运行了test1发现一直没有出结果那么可能是因为你电脑的数据库中不存在test这个数据库。
运行了test2程序进入死循环关闭程序运行后编译器报错如下
在这里插入图片描述
那么能肯定你电脑的数据库中一定没有名为test的这个数据库。

代码解析

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

提取properties文件

写完上述程序会发现,当遇见需要求改jdbc驱动器或是数据库地址时就需要去修改源代码,这就构成了耦合。将对数据的配置参数信息写入properties配置文件中,进行解耦操作。
在这里插入图片描述
新建jdbc.properties:

jdbc.Driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=root

配置文件的设置中,等号左边是key,右边是value
DataSourceTest.java文件中新增以下代码块:

    @Test
    //测试手动创建c3p数据源(加载properties配置文件)
    public void test3() throws Exception{
        //读取配置文件,专门用于读取properties文件,不需要再写后缀名,且它默认是从类路径下开始读取也就是说从resources目录下开始读取
        ResourceBundle rb = ResourceBundle.getBundle("jdbc");
        //读到文件后开始进行赋值
        String driver = rb.getString("jdbc.Driver");//填入key获得配置文件中对应的value
        String url = rb.getString("jdbc.url");
        String username = rb.getString("jdbc.username");
        String password = rb.getString("jdbc.password");
        //创建数据源对象 设置连接参数
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(driver);
        dataSource.setJdbcUrl(url);
        dataSource.setUser(username);
        dataSource.setPassword(password);

        Connection connection = dataSource.getConnection();
        System.out.println(connection);
        connection.close();
    }

运行结果

test3:connection的结果被打印出,证明连接成功
在这里插入图片描述

代码解析

在这里插入图片描述

Spring配置数据源

在maven中导入spring-context依赖

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.5.RELEASE</version>
        </dependency>

在resource文件夹下创建jdbc.properties文件

jdbc.Driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=root

在resource文件夹下创建applicationContext.xml文件
在这里插入图片描述
在这里插入图片描述
如果在创建时没有看见Spring Config的按钮,应该是没有刷新maven依赖的原因,把maven文件重新导入一下就可能会出现。
applicationContext.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
            <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test"></property>
            <property name="user" value="root"></property>
            <property name="password" value="root"></property>
        </bean>
</beans>

DataSourceTest.java文件中新增以下代码块:

    @Test
    //测试Spring容器去产生数据源对象
    public void test4() throws Exception{
        ApplicationContext appletContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        DataSource dataSource = appletContext.getBean(DataSource.class);
//        ComboPooledDataSource dataSource = appletContext.getBean("dataSource", ComboPooledDataSource.class);
        //以上是两种获得bean的方式
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
        connection.close();
    }

运行结果

在这里插入图片描述

常见错误

从appletContext中使用了getBean方法获得的DataSource对象,但是dataSource并找不到getConnection方法,极大可能是因为导错包了!!!
导入:import javax.sql.DataSource;
极有可能导入了:import javax.activation.DataSource;(错误的)

Spring引入外部properties文件

在spring开发中,一般都会将数据库的配置文件数据与spring配置相分离,但在上一个案例中,在properties.xml文件中,直接写入的了数据库的配置
在这里插入图片描述
在以下示例中,将使用context命名空间引入外部的properties文件,然后通过文件中配置的属性进行配置。
applicationContext.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: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">

    <!--加载外部的properties文件-->
    <context:property-placeholder location="classpath:jdbc.properties" />

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.Driver}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>
</beans>

代码解析

在这里插入图片描述
在最前的两个网址不需要去背,xmlns-context配置中的路劲地址不需要背诵,只需要将xmlns这个配置复制下来,然后在冒号后面加上context,将网址中的beans改成context即可完成改配置。
在xsi-schemaLocation=…的第二个网址中,只需要将第一个网址复制下来,然后将其中的beans都修改为context即可完成该配置。
修改完xml配置后运行text4

常见错误


Namespace ‘context’ is not bound
在这里插入图片描述
该错误说明在配置文件applicationContext.xml中没有设置context的命名空间,只需要在配置中写上context的命名空间以及地址就能够解决这个bug。
在这里插入图片描述

aused by: org.xml.sax.SAXParseException; lineNumber: 10; columnNumber: 74; cvc-complex-type.2.4.c: 通配符的匹配很全面, 但无法找到元素 ‘context:property-placeholder’ 的声明。
在这里插入图片描述
以上错误表示在配置文件中设置了某个命名空间,但是在schemaLocation设置中没有设置对应的地址,或是因为模板的地址配置错误了。
没有写模板地址:
在这里插入图片描述
以该错误为例,只需要加上context对应的模板空间地址即可解决该bug。
写了模板地址但是写错了:
在这里插入图片描述
如果地址是错误的只需要修改为正确的模板地址即可。

运行结果

在这里插入图片描述
能够成功打印出地址,说明在xml中的配置文件是正确可行的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值