依赖jar包:
c3p0-0.9.1.2.jar
com.springsource.net.sf.cglib-2.2.0.jar
com.springsource.org.aopalliance-1.0.0.jar
com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
commons-logging-1.1.3.jar
mysql-connector-java-5.1.7-bin.jar
ojdbc6.jar
spring-aop-4.0.0.RELEASE.jar
spring-aspects-4.0.0.RELEASE.jar
spring-beans-4.0.0.RELEASE.jar
spring-context-4.0.0.RELEASE.jar
spring-core-4.0.0.RELEASE.jar
spring-expression-4.0.0.RELEASE.jar
spring-jdbc-4.0.0.RELEASE.jar
spring-orm-4.0.0.RELEASE.jar
spring-tx-4.0.0.RELEASE.jar
spring-web-4.0.0.RELEASE.jar
spring-webmvc-4.0.0.RELEASE.jar
新建java project,命名spring-1
在spring-1项目下新建文件夹lib,将依赖的jar包复制到lib文件夹。选中jar包,右键——》Build Path——》add to Build Path,使得java项目可以引用外部文件。
单击项目名spring-1,
右键——》properties——》java compiler
取消 user compliance from execution environment....的勾选
compiler compliance level选择最高等级,在此为1.7,确认
src目录下,新建spring bean configure file,取名applicationContext.xml
namespaces勾选context命名空间
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="user" value="scott"></property> <property name="password" value="zjvta"></property> <property name="jdbcUrl" value="jdbc:oracle:thin:@localhost:1521:ZJVTA"></property> <property name="driverClass" value="oracle.jdbc.driver.OracleDriver"></property> <property name="initialPoolSize" value="5"></property> <property name="maxPoolSize" value="10"></property> </bean>
单元测试的类名为:JDBCTest
修改JDBCTest.java中内容如下:
package com.spring.jdbc; import java.sql.SQLException; import javax.sql.DataSource; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class JDBCTest { //创建spring的IOC容器 private ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); @Test public void testDataSource() throws SQLException { DataSource dataSource = ctx.getBean(DataSource.class); System.out.println(dataSource.getConnection()); } }
打印出如下信息,说明连接数据库正常。