zoukankan      html  css  js  c++  java
  • Spring初学之使用外部配置文件dataSource

    一、在Spring的基础上还要另外导入c3p0包和mysql的驱动包。

    二、配置文件,

    jdbc.propertices:这里只做了一些简单配置

    user=root
    password=123
    driverClass=com.mysql.jdbc.Driver
    jdbcUrl=jdbc:mysql:///test

    三、spring配置文件:

    <?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.3.xsd">
    
    <!-- 导入外部配置文件-->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="${user}"></property>
        <property name="password" value="${password}"></property>
        <property name="driverClass" value="${driverClass}"></property>
        <property name="jdbcUrl" value="${jdbcUrl}"></property>
    </bean>
    
    
    </beans>

    四、测试:

    package spring.beans.properties.test;
    
    import java.sql.SQLException;
    
    import javax.sql.DataSource;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class Main {
    
        public static void main(String[] args) throws SQLException {
            ApplicationContext ctx=new ClassPathXmlApplicationContext("beans-properties.xml");
            
            DataSource dataSource=(DataSource) ctx.getBean("dataSource");
            System.out.println(dataSource.getConnection());
        }
    
    }

    五、输出

      数据库中有对应数据库test,并配置成功,会输出

    com.mchange.v2.c3p0.impl.NewProxyConnection@28ac3dc3
  • 相关阅读:
    PAT (Basic Level) Practise 1013 数素数
    PAT (Basic Level) Practise 1014 福尔摩斯的约会
    codeforces 814B.An express train to reveries 解题报告
    KMP算法
    rsync工具
    codeforces 777C.Alyona and Spreadsheet 解题报告
    codeforces 798C.Mike and gcd problem 解题报告
    nginx + tomcat多实例
    MongoDB副本集
    指针的艺术(转载)
  • 原文地址:https://www.cnblogs.com/hyyq/p/6701691.html
Copyright © 2011-2022 走看看