依賴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>
在該目錄下新建單元測試案例,JUnit Test Case
單元測試的類名爲: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());
}
}
單元測試,鼠標移動到testDataSource,右鍵——》debug as——》junit Test
打印出如下信息,說明連接數據庫正常。