下面会通过一个获得数据源的例子来比较下传统编码模式和IoC编码模式的不同。首先,在传统编码方式下,我们可能这样获得数据源并显示结果:
package
com.lnic.ioc;
import
javax.sql.DataSource;
import
java.sql.Connection;
import
java.sql.Statement;
import
java.sql.ResultSet;
import
java.sql.SQLException;
import
org.apache.commons.dbcp.BasicDataSource;
public
class
BasicDataSourceExample
{ public static void main(String[] args) { DataSource dataSource = setupDataSource(); // 创建JDBC数据源 Connection conn = null; Statement stmt = null; ResultSet rset = null; try { conn = dataSource.getConnection(); stmt = conn.createStatement(); rset = stmt.executeQuery("select * from user"); System.out.println("Basic DataSource executing results:"); int numcols = rset.getMetaData().getColumnCount(); while (rset.next()) { for (int i = 1; i <= numcols; i++) { System.out.print("/t" + rset.getString(i)); } System.out.println(""); } } catch (SQLException e) { e.printStackTrace(); } finally { try { rset.close(); } catch (Exception e) { } try { stmt.close(); } catch (Exception e) { } try { conn.close(); } catch (Exception e) { } } } // 创建数据源 public static DataSource setupDataSource() { BasicDataSource ds = new BasicDataSource(); ds.setDriverClassName("com.mysql.jdbc.Driver"); ds.setUsername("root"); ds.setPassword("131421"); ds.setUrl("jdbc:mysql://localhost:3306/test"); return ds; } // 提示数据源状态 public static void printDataSourceStats(DataSource ds) throws SQLException { BasicDataSource bds = (BasicDataSource) ds; System.out.println("NumActive: " + bds.getNumActive()); System.out.println("NumIdle: " + bds.getNumIdle()); } // 关闭数据源 public static void shutdownDataSource(DataSource ds) throws SQLException { BasicDataSource bds = (BasicDataSource) ds; bds.close(); }}
这个累的测试结果显示:
Basic DataSource executing results:
123 matthew YunNanUniversity
1 lidexian YunNanUniversity
2 zhangzili HunanUniversity
而在Spring 的IoC容器的帮助下我们的编码会更简单和灵活。首先,定义个Spring的配置文件:applicationContext.xml。在这个配置文件中,我们配置了三个bean组件,代表不同的数据库数据源。然后,通过配置jdbcTemplate来启用需要的具体数据库数据源。如下:我们采用的MySql数据源。
<?
xml version="1.0" encoding="UTF-8"
?>
<!
DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"
>
<
beans
>
<
bean
id
="oracle_dataSource"
class
="org.apache.commons.dbcp.BasicDataSource"
destroy-method
="close"
>
<
property
name
="driverClassName"
value
="oracle.jdbc.driver.OracleDriver"
/>
<
property
name
="url"
value
="jdbc:oracle:thin:@localhost:1521:cyberdb"
/>
<
property
name
="username"
value
="scott"
/>
<
property
name
="password"
value
="tiger"
/>
</
bean
>
<
bean
id
="mysql_dataSource"
class
="org.apache.commons.dbcp.BasicDataSource"
destroy-method
="close"
>
<
property
name
="driverClassName"
value
="com.mysql.jdbc.Driver"
/>
<
property
name
="url"
value
="jdbc:mysql://localhost:3306/test"
/>
<
property
name
="username"
value
="root"
/>
<
property
name
="password"
value
="131421"
/>
</
bean
>
<
bean
id
="linux_oracle_dataSource"
class
="org.apache.commons.dbcp.BasicDataSource"
destroy-method
="close"
>
<
property
name
="driverClassName"
value
="oracle.jdbc.driver.OracleDriver"
/>
<
property
name
="url"
value
="jdbc:oracle:thin:@192.168.0.3:1521:linuxdb"
/>
<
property
name
="username"
value
="scott"
/>
<
property
name
="password"
value
="tiger"
/>
</
bean
>
<
bean
id
="jdbcTemplate"
class
="org.springframework.jdbc.core.JdbcTemplate"
lazy-init
="true"
>
<
property
name
="dataSource"
>
<
ref
local
="mysql_dataSource"
/>
</
property
>
</
bean
>
</
beans
>
然后,如下在代码中通过载入Spring的配置文件,并初始化bean组件:jdbcTemplate得到数据源,并完成数据查询。可以看出比传统的方法简单和灵活多了,只需要简单配置即可完成。
package
com.lnic.ioc;
import
java.sql.ResultSet;
import
java.sql.SQLException;
import
java.util.ArrayList;
import
java.util.List;
import
org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
import
org.springframework.jdbc.core.JdbcTemplate;
import
org.springframework.jdbc.core.RowCallbackHandler;
public
class
IocDataSourceExample
{ public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext( "com/lnic/ioc/applicationContext.xml");//载入spring配置文件applicationContext.xml String sql = "select * from user"; JdbcTemplate jt = (JdbcTemplate) ctx.getBean("jdbcTemplate");//这里采用spring的JdbcTemplate,通过spring的配置文件启用mysql_dataSource数据源。 jt.query(sql, new RowCallbackHandler() { public void processRow(ResultSet rs) throws SQLException { // do something with the rowdata - like create a new // object and add it to the List in the enclosing code System.out.println("IocDataSource executing results:"); int numcols = rs.getMetaData().getColumnCount(); do { for (int i = 1; i <= numcols; i++) { System.out.print("/t" + rs.getString(i)); } System.out.println(""); } while (rs.next()); } }); }}
代码输出如下:
IocDataSource executing results:
123 matthew YunNanUniversity
1 lidexian YunNanUniversity
2 zhangzili HunanUniversity