第一:建立類繼承ServletContextListener
package com.controler;
import com.mysql.jdbc.AbandonedConnectionCleanupThread;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;
@WebListener
public class ContextFinalizer implements ServletContextListener {
public void contextInitialized(ServletContextEvent sce) {
}
public void contextDestroyed(ServletContextEvent sce) {
Enumeration<Driver> drivers = DriverManager.getDrivers();
Driver d = null;
while (drivers.hasMoreElements()) {
try {
d = drivers.nextElement();
DriverManager.deregisterDriver(d);
System.out.println(String.format("ContextFinalizer:Driver %s deregistered", d));
} catch (SQLException ex) {
System.out.println(String.format("ContextFinalizer:Error deregistering driver %s", d) + ":" + ex);
}
}
try {
AbandonedConnectionCleanupThread.shutdown();
} catch (InterruptedException e) {
System.out.println("ContextFinalizer:SEVERE problem cleaning up: " + e.getMessage());
e.printStackTrace();
}
}
}
第二:在spring配置c3po連接配接池的檔案裡加入屬性:
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close" ></bean>