Code

package xgn.jdbc;

import java.io.InputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.LinkedList;
import java.util.Properties;

/***
 * 数据库连接池实现类
 * @author dream
 *
 */
public class JDBCPool {
 //存放连接的集合
 private static LinkedList<Connection> dblist=new LinkedList<Connection>();
 //连接池容量
 private static final int number=100;
 static{
  try{
   Properties config=new Properties();
   InputStream in= JDBCPool.class.getClassLoader().getResourceAsStream("config.properties");
   config.load(in);
   for(int i=0;i<number;i++){
    Connection cn= DriverManager.getConnection(config.getProperty("Connstr"),config.getProperty("user"),config.getProperty("pwd"));
    ConnectionProxy conn=new ConnectionProxy(cn);
    Connection proxycn=conn.getConnectionProxy(cn,new Class[]{Connection.class},conn);
    dblist.addFirst(proxycn);
   }
  }catch(Exception ex){
   throw new RuntimeException(ex);
  }
 }
 public static void recoverConnection(Connection cn){
  dblist.addFirst(cn);
 }
 public static Connection getConnection(){
  if(dblist.size()<=0){
   throw new RuntimeException("数据库连接池无数据库连接!");
  }
  return dblist.removeFirst();
 }
 public static int getConnectionNumber(){
  return dblist.size();
 }
 
 /***
  * 数据库连接代理类
  * @author dream
  *
  */
 public static class ConnectionProxy implements InvocationHandler {
  private Object obj=null;
  private Object proxyobj=null;
  @Override
  public Object invoke(Object arg0, Method arg1, Object[] arg2)throws Throwable {
   Object ret=null;//方法返回值
   if(arg1.getName()=="close"){
    System.out.println("close");
    JDBCPool.recoverConnection((Connection)this.proxyobj);
    return ret;
   }
   ret=arg1.invoke(this.obj, arg2);
   return ret;
  }
  public ConnectionProxy(Connection cn){
   this.obj=cn;
  }
 
  public Connection getConnectionProxy(Connection cn,Class[] cls,InvocationHandler h){
   this.proxyobj= Proxy.newProxyInstance(cn.getClass().getClassLoader(),cls,h);
   return (Connection)this.proxyobj;
  }
 
 }
}

  常用的数据库连接池有:DBCP、tomcat 的数据库连接池(内部也是DBCP)、C3P0等。