Spring数据源的灵活配置巧应用
来源: 框架 Spring | 作者: ITeduer | 发布: 2008-5-08 00:00
四、写测试类
package com.lavasoft.dbtest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* Created by IntelliJ IDEA.
* File: Test.java
* User: leizhimin
* Date: 2008-2-21 14:41:49
* Spring 数据源应用测试
*/
public class Test {
private static final Log log = LogFactory.getLog(Test.class);
public static void main(String args[]) {
Test.test();
}
public static void test() {
String testSql = "select * from t_user";
Connection conn = DBUtil.makeConnection();
Statement stmt = null;
try {
stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.CLOSE_CURSORS_AT_COMMIT);
ResultSet rs = stmt.executeQuery(testSql);
while (rs.next()) {
String firstName = rs.getString("firstname");
String lastName = rs.getString("lastname");
System.out.println(firstName + " " + lastName);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
log.info("关闭Statement对象出现异常!");
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
log.error("关闭数据库连接失败!");
e.printStackTrace();
}
}
}
}
}
测试运行结果:
haha hehe
lei aaa
Process finished with exit code 0
五、数据源置换
Spring实现的DriverManagerDataSource并没有提供连接池的功能,只是用来作简单的单机连接测试,并不适合使用于真正的项目当中,可以考虑用比较成熟的数据连接池来取代。Apache DBCP连接池是不错,如要要替换,则需要加载DBCP相关的工具包。
现在所使用的是org.apache.commons.dbcp.BasicDataSource作为注入的DataSource实例,为了使用DBCP 的功能,您需要在Classpath路径中设定commons-dbcp.jar、commons-pool.jar与commons- collections.jar。注意到在dataSource上设定了"destroy-method"属性,如此可以确保BeanFactory在关闭时也一并关闭BasicDataSource。
六、使用JNDI数据源
如果您的Servlet容器提供了JNDI(Java Naming and Directory Interface)的DataSource,您也可以简单的换上这个DataSource:
class="org.springframework.indi.JndiObjectFactoryBean">
为了使用org.springframework.indi.JndiObjectFactoryBean,您需要spring-context.jar,"jndiName"实际上要根据您所设定的JNDI查询名称。
