Java AOP实战 寻找SQL的引用路径

一个遗留系统,直接用connection和statement操作数据库,SQL信息都没打出来,不好查问题。

于是想到AOP,在执行executeQuery方法时,把参数截获打印出来。。

 

package com.test;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Statement;

public class ConnectProxy implements InvocationHandler {
 private Object delegate;

 public Object bind(Object delegate) {
  this.delegate = delegate;
  return Proxy.newProxyInstance(delegate.getClass().getClassLoader(), delegate.getClass

().getInterfaces(), this);
 }

 public Object invoke(Object arg0, Method arg1, Object[] arg2) throws Throwable {
  if (arg1.getName().equals("createStatement"))
  {
   ConnectProxy conn = new ConnectProxy();
   Object statement = arg1.invoke(delegate, arg2);
   Statement stmt = (Statement)conn.bind(statement);
   return stmt;
  }
  if (arg1.getName().equals("executeQuery"))
  {
   System.out.println(arg2[0]);
   System.out.println(Thread.currentThread().getStackTrace()[3]);
  }
  Object result = arg1.invoke(delegate, arg2);
  return result;
 }
}
使用:

public Connection getConnection()
{
 Connection conn = DriverManager.getConnection(url, user, password);
 ConnectProxy connProxy = new ConnectProxy();
 return (Connection)connProxy.bind(conn);
}

通过这样的操作,我们就能在调用处加入日志或者打印SQL,甚至打印StackTrace,再也不用为找一个动态SQL是从哪儿来的而痛苦

了。

 

posted @ 2008-12-23 16:35  好好学习,天天进步  阅读(264)  评论(0编辑  收藏  举报