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

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


回答:

自己代理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

}

}

以上是 cglib怎么拦截java.sql.Statement类? 的全部内容, 来源链接: utcz.com/p/945148.html

回到顶部