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是从哪儿来的而痛苦

了。

 

转载于:https://www.cnblogs.com/marryZhan/archive/2008/12/23/2213970.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值