当前位置: 首页 > 知识库问答 >
问题:

关于Cglib代理MethodInterceptor回调参数的问题

赫连法
2023-03-14

在使用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();

我对intercept方法的参数的含义感到困惑:

  @Override
  public Object intercept(
      Object o,
      Method method,
      Object[] objects,
      MethodProxy methodProxy) throws Throwable {
  }

问题:methodmethodproxy参数是什么?它们之间有什么区别?当我使用methodProxy调用时,它也起作用,这让我感到困惑。

Object obj = method.invoke(target, objects);

// This also works, why?
// Object obj = methodProxy.invoke(target, objects);

共有1个答案

年业
2023-03-14

Javadoc表示:

原始方法既可以通过使用method对象的正常反射调用,也可以通过使用MethodProxy(更快)调用。

我不知道是什么让它更快。

 类似资料:
  • 1) 应该接受参数int,但为什么以下内容可以编译? 应返回,而不是int。 2)为什么下面不能编译?

  • 我正在使用spring-boot 2.3.9和spring-security以及keycloak 12.0.4。 和我的服务bean创建配置 编辑:这可能与Spring-Cloud-Starter-Sleuth有关。如果我移除这个依赖关系,所有的事情就会像预期的那样工作。但我也需要侦探。

  • 我有很多个页面,大部分都是上下结构,上面查询条件,下面表格,然后表格后面是操作按钮,点击详情url带上查询条件跳转到详情,返回的时候参数没了,现在需要返回的时候保留参数 问题: 因为页面比较多,请问怎么能在最小的改动下实现这个需求 Ps:查询条件的表单都是每个页面独立使用的,没有统一封装

  • 我在freecodecamp.org https://www.freecodecamp.org/learn/javascript-algorithors-and-data-structures/mediatory-algorith-scripting/arguments-optional 下面的代码就是我写的。在该代码中,addTogether(2)(3)应为5。但相反,addTogether(2

  • Spring文档说明: 输出: 同样-通过实验-CGLIB库(不使用spring,使用增强器类)也允许代理包级方法。 更新 我想我找到了接受公共方法的这种行为只会发生的地方。它发生在处,这是切入点()使用的。 来自代码: