美文网首页Spring
spring 配置c3p0连接池

spring 配置c3p0连接池

作者: DouDouZH | 来源:发表于2018-05-28 20:07 被阅读5次

    一、导入jar包

    image.png

    二、步骤

    (1)把链接驱动类、链接、用户名和密码等在配置文件中进行配置
    • 新建db.properties


      image.png
    • 写上配置


      image.png
    • 把db.properties引入applicationContext.xml配置文件


      image.png
    (2)在配置文件中配置ComboPooledDataSource类
    image.png
    (3)在测试类里测试是否配置成功

    二、代码

    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-4.0.xsd">
        <!--  value 从配置文件里面 db.properties中取值 -->
        <!-- 加载配置文件 -->
        <context:property-placeholder location="classpath:db.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.user}"></property>
                <property name="password" value="${jdbc.password}"></property>
        </bean>      
      
    </beans>
    

    测试类TestSpringC3p0.java

    package work.zhangdoudou.Test;
    
    import static org.junit.Assert.*;
    
    import java.sql.Connection;
    import java.sql.SQLException;
    
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    import com.mchange.v2.c3p0.ComboPooledDataSource;
    
    public class TestSpringC3p0 {
    
        @Test
        public void test() throws SQLException {
            ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
            ComboPooledDataSource dataSource=(ComboPooledDataSource)context.getBean("dataSource");
            Connection connection=dataSource.getConnection();
            System.out.println(connection); 
        }
    }
    

    三、运行结果

    image.png

    相关文章

      网友评论

        本文标题:spring 配置c3p0连接池

        本文链接:https://www.haomeiwen.com/subject/npcnjftx.html