DriverManagerDataSource 並沒有提供連接池的功能,,只能作作簡單的單機連接測試,實際上並不能使用於真正的專案之中,您可以使用DBCP以獲得連接池的功能,如果您使用 Spring,則置換DataSource並不需要修改程式原始碼,只要修改Bean定義檔就可以了,例如修改一下 DataSource 注入 中的beans-config.xml如下:
- beans-config.xml
<?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="dataSource"
class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<property name="url">
<value>jdbc:mysql://localhost:3306/demo</value>
</property>
<property name="username">
<value>caterpillar</value>
</property>
<property name="password">
<value>123456</value>
</property>
</bean>
<bean id="userDAO"
class="onlyfun.caterpillar.UserDAO">
<property name="dataSource">
<ref bean="dataSource"/>
</property>
</bean>
</beans>
現在所使用的是org.apache.commons.dbcp.BasicDataSource作為注入的DataSource實例,為了使用DBCP 的功能,您需要在Classpath路徑中設定commons-dbcp.jar、commons-pool.jar與commons- collections.jar,這些都可以在 Spring的相依版本中的lib目錄下找到。
注意到在dataSource上設定了"destroy-method"屬性,如此可以確保BeanFactory在關閉時也一併關閉BasicDataSource。
如果您的Servlet容器提供了JNDI(Java Naming and Directory Interface)的DataSource,您也可以簡單的換上這個DataSource:
...
<bean id="dataSource"
class="org.springframework.indi.JndiObjectFactoryBean">
<property name="jndiName">
<value>jdbc/demo</value>
</property>
</bean>
...
<bean id="dataSource"
class="org.springframework.indi.JndiObjectFactoryBean">
<property name="jndiName">
<value>jdbc/demo</value>
</property>
</bean>
...
為了使用org.springframework.indi.JndiObjectFactoryBean,您需要spring-context.jar,"jndiName"實際上要根據您所設定的JNDI查詢名稱。