使用commons-dbcp-1.2.2.jar的DataSource,发现每次动态编译后连接池中的连接不会释放,新的连接池建立有mssql多出一组连接,只有重新启动tomcat或weblogic才可以释放。
package aaplan.dbutil; import java.io.InputStream; import java.util.Properties; import java.sql.*; import javax.sql.DataSource; import org.apache.commons.dbcp.BasicDataSourceFactory; public class JdbcUtil { private static DataSource dataSource=null; /** * @param args */ public static Connection getConnection() throws SQLException { return dataSource.getConnection(); } public static DataSource getDataSource() { return dataSource; } public static void release() { if(dataSource !=null){ try { ((org.apache.commons.dbcp.BasicDataSource)dataSource).close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } static{ try{ Properties properties=new Properties(); InputStream inputStream= JdbcUtil.class.getClassLoader().getResourceAsStream("dbcp.properties"); properties.load(inputStream); inputStream.close(); dataSource =BasicDataSourceFactory.createDataSource(properties); System.out.println(dataSource); }catch(Exception e){ e.printStackTrace(); throw new RuntimeException("JdbcUtil Init Error!"); } } }
package aaplan.dbutil; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; /** * Application Lifecycle Listener implementation class DataSorceMgrListener * */ public class DataSorceMgrListener implements ServletContextListener { /** * Default constructor. */ public DataSorceMgrListener() { // TODO Auto-generated constructor stub } /** * @see ServletContextListener#contextInitialized(ServletContextEvent) */ public void contextInitialized(ServletContextEvent arg0) { // TODO Auto-generated method stub System.out.println("Init context!"); JdbcUtil.getDataSource(); } /** * @see ServletContextListener#contextDestroyed(ServletContextEvent) */ public void contextDestroyed(ServletContextEvent arg0) { System.out.println("Destoryed Context!"); JdbcUtil.release(); } }
解决,写了个ServerContextListener,在里面的Destroyed中人工释放