spring数据源抽取

Posted 温暖了寂寞

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring数据源抽取相关的知识,希望对你有一定的参考价值。

 

   @Test
    //测试Spring容器产生数据源对象
    public void test4() throws Exception 
        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        DataSource dataSource = app.getBean(DataSource.class);
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
        connection.close();
    

    @Test
    //测试手动创建 c3p0 数据源(加载properties配置文件)
    public void test3() 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 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();

    

    @Test
    //测试手动创建 druid 数据源
    public void test2() throws Exception 
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/test?&serverTimezone=UTC");
        dataSource.setUsername("root");
        dataSource.setPassword("1234");
        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");
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test?useSSL=false");
        dataSource.setUser("root");
        dataSource.setPassword("1234");
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
        connection.close();
    

 

    <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>

 

以上是关于spring数据源抽取的主要内容,如果未能解决你的问题,请参考以下文章

springmvc+spring-security+mybatis +redis 框架抽取

Spring Cloud ( openFeign 服务发现配置公共client抽取 )

使用HibernateDaoSupport抽取BaseDao

Spring框架基础2

Spring框架 AOP

Spring中的AOP