Spring配置数据源

数据源(连接池)的作用

  • 数据源的目的时提高程序性能
  • 先实例化数据源,初始化部分连接资源
  • 使用连接资源时从数据源获取
  • 使用完毕后将连接资源归给数据源

常见数据源:DBCP,C3P0,BoneCP....

数据源开发步骤

  • 导入数据源坐标,数据库驱动坐标(porm中)
  • 创建数据源对象
  • 设置数据源基本连接数据(驱动,地址,用户名,密码)
  • 使用数据源获取连接资源和归坏连接资源

Spring配置数据源

可以将DataSource的创建全交给Spring容器去完成

  • DataSource有无参构造方法,而Spring默认就是通过无参构造方法实例化对象的
  • DataSource要想使用需要通过set方法设置数据库连接信息,而Spring可以通过set方法进行字符串注入
<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>

测试从容器中获取数据源

ApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml");
DataSource dataSource = app.getBean(DataSource.class);//写xml中id,或者class文件名
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();

抽取jdbc配置文件

再xml配置文件中加载properties配置

  • 首先引入context命名空间和约束路径
    命名空间:直接加上
    xmlns:context="http://www.springframework.org/schema/context"
    约束路径:xsi:schemaLocation后加上
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
<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"/>
    <!--${key}方式直接引用-->
    <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>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容