cglib怎么拦截java.sql.Statement类?

我不知道咋拦截,我想不修改源代码的情况下进行拦截增强,我发现使用cglib需要手动使用Enhancer#create()方法创建一个代理类,手动调用才能触发Callback的钩子函数

阅读 1.4k
2 个回答

自己代理connection,返回Statement的方法你返回代理对象就行了
只要你改造datasource的getConnection方法,业务代码不需要改动

1.用 CGLIB 对 java.sql.Statement 类来进行拦截增强:

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

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

public class StatementInterceptor implements MethodInterceptor {

    private Statement statement;

    public StatementInterceptor(Statement statement) {
        this.statement = statement;
    }

    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        System.out.println("Before invoking " + method.getName());
        Object result = method.invoke(statement, args);
        System.out.println("After invoking " + method.getName());
        return result;
    }

    public static Statement createProxy(Statement statement) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(Statement.class);
        enhancer.setCallback(new StatementInterceptor(statement));
        return (Statement) enhancer.create();
    }

    public static void main(String[] args) throws Exception {
        // Assuming you have an actual Statement object named 'statement'
        Statement statement = ...;

        Statement proxyStatement = StatementInterceptor.createProxy(statement);
        // Use proxyStatement instead of the original 'statement' object
    }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏