【发布时间】:2021-02-14 11:34:36
【问题描述】:
在使用Spring Cglib代理时,我们需要实现一个MethodInterceptor回调,我对这个回调有些问题。为了更清楚,让我们用一个简单的例子。
这是我的目标类 MyPlay.java
public class MyPlay {
public void play() {
System.out.println("MyPlay test...");
}
}
我创建了一个回调:
public class CglibMethodInterceptor implements MethodInterceptor {
private Object target;
public CglibMethodInterceptor(Object target) {
this.target = target;
}
public Object getProxy() {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(target.getClass());
enhancer.setCallback(this);
return enhancer.create();
}
@Override
public Object intercept(
Object o,
Method method,
Object[] objects,
MethodProxy methodProxy) throws Throwable {
System.out.println("CGLIB prep work...");
Object obj = method.invoke(target, objects);
System.out.println("CGLIB post work...");
return obj;
}
}
在我的主课中:
MyPlay myPlay = new MyPlay();
cglibMethodInterceptor = new CglibMethodInterceptor(myPlay);
Play myPlayProxy = (Play) cglibMethodInterceptor.getProxy();
myPlay.play();
myPlayProxy.play();
我对拦截方法的参数含义感到困惑:
@Override
public Object intercept(
Object o,
Method method,
Object[] objects,
MethodProxy methodProxy) throws Throwable {
}
所以,我在 myPlayProxy.play() 处设置了一个断点并进入其中。我截图了:
问题:method 和methodProxy 参数是什么?它们之间有什么区别?当我使用methodProxy调用时,它也起作用了,这让我感到困惑。
Object obj = method.invoke(target, objects);
// This also works, why?
// Object obj = methodProxy.invoke(target, objects);
【问题讨论】: