java cglib动态代理

cglib动态代理,为什么a()调用当前类的b(),这个b()是父类的b(),而不是cglib生成的子类的b()呢?

@Component
public class MyTest {
    public void a() {
        System.out.println("it's a");
        b();
    }
    public void b() {
        System.out.println("it's b");
    }
}

@Aspect
@Component
@Slf4j
@Getter
public class AspectLog {
    @Pointcut("execution(public * com.vae1970.demo.aspect.MyTest.*(..))")
    public void pointcut() {
    }
    
    @Before("pointcut()")
    public void before(JoinPoint jp) {
        Method method = (MethodSignature) jp.getSignature().getMethod();
        System.out.println("log: function " + method.getName());
    }
}

@RestController
public class TestController {
    @Autowired
    private MyTest myTest;

    @GetMapping("/aspect")
    public String aspect() {
        myTest.a();
        return "ok";
    }
}

期望输出

log: function a
it's a
log: function b
it's b

实际输出

log: function a
it's a
it's b

我查看了cglib生成的MyTest类,a()和b()都做了代理,那为什么实际执行的时候,没有执行代理类的b()呢?

阅读 2.2k
2 个回答

因为代理类实际调用的就是原方法。
只不过在原方法的前后增加了自定义的方法,生成的代理类而已。
在spring中用cglib你可以看org.springframework.aop.framework.CglibAopProxy.DynamicAdvisedInterceptor类里的intercept()方法,最终执行你的a()方法的是下面这句

retVal = methodProxy.invoke(target, argsToUse);

其中这个target参数就是被代理的实体类,即你这里的myTest属性(没被代理的类)

在MyTest里面注入MyTest再调用b方法即可

@Component
public class MyTest {
    @Autowired
    private MyTest myTest;
    public void a() {
        System.out.println("it's a");
        myTest.b();
    }
    public void b() {
        System.out.println("it's b");
    }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题