Spring-配置数据源


传统配置使用数据源

配置mysql、junit、c3p0和德鲁伊

    
        
            org.springframework
            spring-context
            5.2.5.RELEASE
        

        
            junit
            junit
            4.10
            test
        

        
            mysql
            mysql-connector-java
            8.0.28
        

        
            c3p0
            c3p0
            0.9.1.2
        

        
            com.alibaba
            druid
            1.0.9
        
    

编写jdbc.properties

注意8版本以下driver路径应为:com.mysql.jdbc.Driver

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/数据库名称
jdbc.username=你的用户名
jdbc.password=你的密码

测试

以c3p0为例

import org.junit.Test;
import java.sql.Connection;
import java.util.ResourceBundle;
import com.mchange.v2.c3p0.ComboPooledDataSource;

    /**
     * 测试c3p0连接数据库
     * @throws Exception
     */
    @Test
    public void test_jdbc() throws Exception{
        // 读取配置文件
        ResourceBundle rb = ResourceBundle.getBundle("jdbc");
        String driver = rb.getString("jdbc.driver");
        String url = rb.getString("jdbc.url");
        String username = rb.getString("jdbc.username");
        String password = rb.getString("jdbc.password");
        // 创建数据源对象,设置链接参数
        ComboPooledDataSource source = new ComboPooledDataSource();
        source.setDriverClass(driver);
        source.setJdbcUrl(url);
        source.setUser(username);
        source.setPassword(password);

        Connection connection = source.getConnection();
        System.out.println(connection);

        connection.close();
    }

通过Bean创建数据源

仍然需要编写配置依赖和jdbc配置文件
我们在上面的例子中创建了第三方的对象

        ComboPooledDataSource source = new ComboPooledDataSource();

并且使用了第三方对象的set方法

        source.setDriverClass(driver);
        source.setJdbcUrl(url);
        source.setUser(username);
        source.setPassword(password);

那我们能否通过Spring配置文件的Bean标签结合set方法注入来帮助我们创建对象?
答案自然是可以的

配置文件书写

注意引入命名空间:

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

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd

完整的编写

<?xml version="1.0" encoding="UTF-8"?>


    
    
    
        
        
        
        
    


测试

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.sql.DataSource;
import java.sql.Connection;

    @Test
    public void test_c3p0() throws Exception{
        ApplicationContext app = new ClassPathXmlApplicationContext("appContext.xml");
        DataSource source = (DataSource) app.getBean("dataSource");
        Connection connection = source.getConnection();
        System.out.println(connection);
        connection.close();
    }