1. 使用spring 如何配置数据源?

    测试如下


  2. <?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">
    
    	
    	<!-- 导入属性文件 -->
    	<context:property-placeholder location="classpath:db.properties"/>
    	<!--  如果你的db.properties 是放在其他文件夹下,引用如下格式  -->
    	<!-- <context:property-placeholder location="classpath:com/spring/entity/db.properties"/> -->
    	
    	<!-- 配置数据源 -->
    	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    		<property name="user" value="${uesr}"></property>
    		<property name="password" value="${password}"></property>
    		<property name="driverClass" value="${driverClass}"></property>
    		<property name="jdbcUrl" value="${jdbcUrl}"></property>
    	</bean>
    </beans>

    3.db.properties 配置文件

    这里用的是oracle 数据库

  3. uesr=zt       // 数据库用户名                 
    password=zt          // 数据库密码
    driverClass=oracle.jdbc.OracleDriver
    jdbcUrl=jdbc:oracle:thin:@localhost:1521:xe

4. 需要导入的jar包

spring 如何配置数据源_配置

5.测试配置是否正确

package com.spring.test;


import java.sql.SQLException;

import javax.sql.DataSource;

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

public class TestSource {
	public static void main(String[] args) throws SQLException {
		
		ApplicationContext ctx = new ClassPathXmlApplicationContext("datasource.xml");
		DataSource source = (DataSource) ctx.getBean("dataSource");
		System.out.println(source.getConnection());
	}
}

结果:com.mchange.v2.c3p0.impl.NewProxyConnection@2f0a87b3

说明配置正确。