Spring配置数据源

目录

数据连接池的作用

使用spring配置数据源

抽取配置文件

定义命名空间


数据连接池的作用

数据源的配置步骤

使用spring配置数据源

   /**
     * 测试手动创建c3po数据连接
     *
     */
    @Test
    public void test() throws PropertyVetoException, SQLException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass("com.mysql.jdbc.Driver");
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
        dataSource.setUser("root");
        dataSource.setPassword("123");
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
        connection.close();
    }
    <bean name="rb" 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="123"></property>
    </bean>

主要是通过spring-bean方法中的通过set发法注入属性来进行

  /**
     * 测试spring创建数据连接
     */
    @Test
    public void test4() throws SQLException {
        ApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml");
        DataSource  rb = (DataSource) app.getBean("rb");
        Connection connection = rb.getConnection();
        System.out.println(connection);
        connection.close();
    }

抽取配置文件

在使用spring进行数据源配置的时候就已经进行了解耦了,但是为了更加方便所以对jdbc的配置进行了抽取

定义命名空间

 xmlns:contest="http://www.springframework.org/schema/context"

http://www.springframework.org/schema/context  http://www.springframework.org/schema/contest/spring-contest.xsd
<contest:property-placeholder location="classpath:jdbc.properties"/>

使用

 <bean name="rb" 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>

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值