学一学Sping中的AOP【代理对象如何被创建?】【方法如何被拦截?】

102 阅读7分钟

一、Work类的代理创建过程

1.1、拦截器查找

 /**
  * 初始化之后的后置处理
  * 因为AnnotationAwareAspectJAutoProxyCreator间接实现了BeanPostProcessor
  */
 // AbstractAutoProxyCreator
 public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
     if (bean != null) {
         Object cacheKey = getCacheKey(bean.getClass(), beanName);
         if (this.earlyProxyReferences.remove(cacheKey) != bean) {
             // 是否需要封装
             return wrapIfNecessary(bean, beanName, cacheKey);
         }
     }
     return bean;
 }
 ​
 protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
     // 省略部分代码...
     
     // 找具体的拦截器
     // 1.ExposeInvocationInterceptor
     // 2.AspectJPointcutAdvisor
     Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
     if (specificInterceptors != DO_NOT_PROXY) {
         this.advisedBeans.put(cacheKey, Boolean.TRUE);
         // 准备创建代理
         Object proxy = createProxy(
                 bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
         this.proxyTypes.put(cacheKey, proxy.getClass());
         return proxy;
     }
 ​
     this.advisedBeans.put(cacheKey, Boolean.FALSE);
     return bean;
 }
 // AbstractAdvisorAutoProxyCreator
 protected Object[] getAdvicesAndAdvisorsForBean(
             Class<?> beanClass, String beanName, @Nullable TargetSource targetSource) {
     // 查找符合条件的Advisor
     List<Advisor> advisors = findEligibleAdvisors(beanClass, beanName);
     if (advisors.isEmpty()) {
         return DO_NOT_PROXY;
     }
     return advisors.toArray();
 }
 ​
 protected List<Advisor> findEligibleAdvisors(Class<?> beanClass, String beanName) {
     // 查找候选的advisor
     // 结果是"org.springframework.aop.aspectj.AspectJPointcutAdvisor#0"
     List<Advisor> candidateAdvisors = findCandidateAdvisors();
     
     // 筛选出符合条件的advisor(能够应用到work上)
     List<Advisor> eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);
     // 扩展advisors
     extendAdvisors(eligibleAdvisors);
     if (!eligibleAdvisors.isEmpty()) {
         eligibleAdvisors = sortAdvisors(eligibleAdvisors);
     }
     return eligibleAdvisors;
 }
 ​
 protected List<Advisor> findCandidateAdvisors() {
         Assert.state(this.advisorRetrievalHelper != null, "No BeanFactoryAdvisorRetrievalHelper available");
     return this.advisorRetrievalHelper.findAdvisorBeans();
 }

1.1.1 查找advisor

 // AnnotationAwareAspectJAutoProxyCreator
 protected List<Advisor> findCandidateAdvisors() {
     // 容器中所有的advisor
     List<Advisor> advisors = super.findCandidateAdvisors();
     // 为容器中所有AspectJ切面创建advisor(主要是注解),本案例中没有
     if (this.aspectJAdvisorsBuilder != null) {
         advisors.addAll(this.aspectJAdvisorsBuilder.buildAspectJAdvisors());
     }
     return advisors;
 }
 // BeanFactoryAdvisorRetrievalHelper
 public List<Advisor> findAdvisorBeans() {
     
     String[] advisorNames = this.cachedAdvisorBeanNames;
     // 省略部分代码...
 ​
     List<Advisor> advisors = new ArrayList<>();
     // 省略部分代码...
     
     // 此处直接从容器的一级缓存获取到了"org.springframework.aop.aspectj.AspectJPointcutAdvisor#0",之前已经实例化
     advisors.add(this.beanFactory.getBean(name, Advisor.class));
             
     // 省略部分代码...
     return advisors;
 }

1.1.2 筛选符合条件的advisor

 // AbstractAdvisorAtuoProxyCreator
 protected List<Advisor> findAdvisorsThatCanApply(
             List<Advisor> candidateAdvisors, Class<?> beanClass, String beanName) {
 ​
     ProxyCreationContext.setCurrentProxiedBeanName(beanName);
     try {
         return AopUtils.findAdvisorsThatCanApply(candidateAdvisors, beanClass);
     }
     finally {
         ProxyCreationContext.setCurrentProxiedBeanName(null);
     }
 }
 // AopUtils
 public static List<Advisor> findAdvisorsThatCanApply(List<Advisor> candidateAdvisors, Class<?> clazz) {
     // 省略部分代码...
     if (canApply(candidate, clazz, hasIntroductions)) {
         eligibleAdvisors.add(candidate);
     }
     return eligibleAdvisors;
 }
 ​
 public static boolean canApply(Advisor advisor, Class<?> targetClass, boolean hasIntroductions) {
     // 省略部分代码...
     PointcutAdvisor pca = (PointcutAdvisor) advisor;
     return canApply(pca.getPointcut(), targetClass, hasIntroductions);
     // 省略部分代码...
 }
 ​
 public static boolean canApply(Pointcut pc, Class<?> targetClass, boolean hasIntroductions) {
     // 省略部分代码...
     IntroductionAwareMethodMatcher introductionAwareMethodMatcher = null;
     if (methodMatcher instanceof IntroductionAwareMethodMatcher) {
         introductionAwareMethodMatcher = (IntroductionAwareMethodMatcher) methodMatcher;
     }
 ​
     Set<Class<?>> classes = new LinkedHashSet<>();
     if (!Proxy.isProxyClass(targetClass)) {
         classes.add(ClassUtils.getUserClass(targetClass));
     }
     classes.addAll(ClassUtils.getAllInterfacesForClassAsSet(targetClass));
     // 遍历work中所有的方法,任一方法匹配上返回true
     for (Class<?> clazz : classes) {
         Method[] methods = ReflectionUtils.getAllDeclaredMethods(clazz);
         for (Method method : methods) {
             if (introductionAwareMethodMatcher != null ?
                     introductionAwareMethodMatcher.matches(method, targetClass, hasIntroductions) :
                     methodMatcher.matches(method, targetClass)) {
                 return true;
             }
         }
     }
 ​
     return false;
 }

1.1.3 扩展advisors

 /**
  * 在通知链的最前面添加ExposeInvocationInterceptor
  * 当使用AspectJ切点表达式及使用AspectJ风格的通知时,这个额外的通知时必须的
  */
 // AspectJAwareAdvisorAutoProxyCreator
 protected void extendAdvisors(List<Advisor> candidateAdvisors) {
     AspectJProxyUtils.makeAdvisorChainAspectJCapableIfNecessary(candidateAdvisors);
 }
 // AspectJProxyUtils
 public static boolean makeAdvisorChainAspectJCapableIfNecessary(List<Advisor> advisors) {
     // Don't add advisors to an empty list; may indicate that proxying is just not required
     if (!advisors.isEmpty()) {
         boolean foundAspectJAdvice = false;
         for (Advisor advisor : advisors) {
             // Be careful not to get the Advice without a guard, as this might eagerly
             // instantiate a non-singleton AspectJ aspect...
             if (isAspectJAdvice(advisor)) {
                 foundAspectJAdvice = true;
                 break;
             }
         }
         if (foundAspectJAdvice && !advisors.contains(ExposeInvocationInterceptor.ADVISOR)) {
             // 添加ExposeInvocationInterceptor
             advisors.add(0, ExposeInvocationInterceptor.ADVISOR);
             return true;
         }
     }
     return false;
 }

1.2、创建代理

1.2.1 代理工厂创建

 // AbstarctAutoProxyCreator
 protected Object createProxy(Class<?> beanClass, @Nullable String beanName,
             @Nullable Object[] specificInterceptors, TargetSource targetSource) {
 ​
     if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
         AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName, beanClass);
     }
 ​
     ProxyFactory proxyFactory = new ProxyFactory();
     proxyFactory.copyFrom(this);
 ​
     if (proxyFactory.isProxyTargetClass()) {
         // Explicit handling of JDK proxy targets and lambdas (for introduction advice scenarios)
         if (Proxy.isProxyClass(beanClass) || ClassUtils.isLambdaClass(beanClass)) {
             // Must allow for introductions; can't just set interfaces to the proxy's interfaces only.
             for (Class<?> ifc : beanClass.getInterfaces()) {
                 proxyFactory.addInterface(ifc);
             }
         }
     } else {
         // No proxyTargetClass flag enforced, let's apply our default checks...
         if (shouldProxyTargetClass(beanClass, beanName)) {
             proxyFactory.setProxyTargetClass(true);
         }
         else {
             evaluateProxyInterfaces(beanClass, proxyFactory);
         }
     }
 ​
     Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
     proxyFactory.addAdvisors(advisors);
     proxyFactory.setTargetSource(targetSource);
     customizeProxyFactory(proxyFactory);
 ​
     proxyFactory.setFrozen(this.freezeProxy);
     if (advisorsPreFiltered()) {
         proxyFactory.setPreFiltered(true);
     }
 ​
     // Use original ClassLoader if bean class not locally loaded in overriding class loader
     ClassLoader classLoader = getProxyClassLoader();
     if (classLoader instanceof SmartClassLoader && classLoader != beanClass.getClassLoader()) {
         classLoader = ((SmartClassLoader) classLoader).getOriginalClassLoader();
     }
     return proxyFactory.getProxy(classLoader);
 }
 // ProxyFactory
 public Object getProxy(@Nullable ClassLoader classLoader) {
     // createAopProxy 创建代理
     // getProxy 获取代理
     return createAopProxy().getProxy(classLoader);
 }

1.2.2 创建Aop代理

 // ProxyCreatorSupport
 protected final synchronized AopProxy createAopProxy() {
     if (!this.active) {
         activate();
     }
     // getAopProxyFactory --> DefalutAopProxyFactory
     return getAopProxyFactory().createAopProxy(this);
 }
 // DefalutAopProxyFactory
 public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
     if (!NativeDetector.inNativeImage() &&
             (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config))) {
         Class<?> targetClass = config.getTargetClass();
         if (targetClass == null) {
             throw new AopConfigException("TargetSource cannot determine target class: " +
                     "Either an interface or a target is required for proxy creation.");
         }
         if (targetClass.isInterface() || Proxy.isProxyClass(targetClass) || ClassUtils.isLambdaClass(targetClass))        {
             return new JdkDynamicAopProxy(config);
         }
         // Cglib代理
         return new ObjenesisCglibAopProxy(config);
     } else {
         return new JdkDynamicAopProxy(config);
     }
 }

1.2.3 Cglib创建代理对象

1.2.3.1 Cglib的基本参数配置
 /**
  * 实际创建代理对象的地方
  */
 // CglibAopProxy
 public Object getProxy(@Nullable ClassLoader classLoader) {
         // 省略部分代码...
 ​
         // Configure CGLIB Enhancer...
         Enhancer enhancer = createEnhancer();
         if (classLoader != null) {
             enhancer.setClassLoader(classLoader);
             if (classLoader instanceof SmartClassLoader &&
                     ((SmartClassLoader) classLoader).isClassReloadable(proxySuperClass)) {
                 enhancer.setUseCache(false);
             }
         }
         enhancer.setSuperclass(proxySuperClass);
         enhancer.setInterfaces(AopProxyUtils.completeProxiedInterfaces(this.advised));
         enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
         enhancer.setStrategy(new ClassLoaderAwareGeneratorStrategy(classLoader));
         // 关注第一个callBack
         Callback[] callbacks = getCallbacks(rootClass);
         Class<?>[] types = new Class<?>[callbacks.length];
         for (int x = 0; x < types.length; x++) {
             types[x] = callbacks[x].getClass();
         }
         enhancer.setCallbackFilter(new ProxyCallbackFilter(
                 this.advised.getConfigurationOnlyCopy(), this.fixedInterceptorMap, this.fixedInterceptorOffset));
         enhancer.setCallbackTypes(types);
 ​
         // 生成代理类并实例化
         return createProxyClassAndInstance(enhancer, callbacks);
         // 省略部分代码...
 }
 ​
 /**
  * 这个方法会返回7种callBack
  * 当前只关注第一个DynamicAdvisedInterceptor
  */
 private Callback[] getCallbacks(Class<?> rootClass) throws Exception {
     boolean exposeProxy = this.advised.isExposeProxy();
     boolean isFrozen = this.advised.isFrozen();
     boolean isStatic = this.advised.getTargetSource().isStatic();
 ​
     // "aop"拦截器 (AOP调用使用)
     Callback aopInterceptor = new DynamicAdvisedInterceptor(this.advised);
 ​
     // 省略部分代码...
 ​
     Callback[] mainCallbacks = new Callback[] {
             aopInterceptor,  // 普通通知
             targetInterceptor,
             new SerializableNoOp(),
             targetDispatcher, this.advisedDispatcher,
             new EqualsInterceptor(this.advised),
             new HashCodeInterceptor(this.advised)
     };
 ​
     Callback[] callbacks;
 ​
     // 省略部分代码...
     callbacks = mainCallbacks;
     return callbacks;
 }
1.2.3.2 代理类的生成及代理对象的创建
 // ObjenesisCglibAopProxy
 protected Object createProxyClassAndInstance(Enhancer enhancer, Callback[] callbacks) {
     // 代理类的生成
     Class<?> proxyClass = enhancer.createClass();
     Object proxyInstance = null;
 ​
     if (objenesis.isWorthTrying()) {
         try {
             // 代理对象的实例化
             proxyInstance = objenesis.newInstance(proxyClass, enhancer.getUseCache());
         } catch (Throwable ex) {
             logger.debug("Unable to instantiate proxy using Objenesis, " +
                     "falling back to regular proxy construction", ex);
         }
     }
     // 省略部分代码...
     
     // 代理类callBacks初始化
     ((Factory) proxyInstance).setCallbacks(callbacks);
     return proxyInstance;
 }

二、客户端调用

2.1 代理对象源码

 // Work$$EnhancerBySpringCGLIB$$3d7749bf
 ​
 /**
  * 这个类就是Cglib动态生成的
  * 可以看到这个类是目标类(Work)的子类
  * 删除了部分equals、clone、toString等非关注点方法相关代码
  * 重点关注doWork方法,我们此前配置的需要增强的方法就是Work中此方法
  */
 public class Work$$EnhancerBySpringCGLIB$$3d7749bf extends Work implements SpringProxy, Advised, Factory {
     private boolean CGLIB$BOUND;
     public static Object CGLIB$FACTORY_DATA;
     private static final ThreadLocal CGLIB$THREAD_CALLBACKS;
     private static final Callback[] CGLIB$STATIC_CALLBACKS;
     private MethodInterceptor CGLIB$CALLBACK_0;
     private MethodInterceptor CGLIB$CALLBACK_1;
     private NoOp CGLIB$CALLBACK_2;
     private Dispatcher CGLIB$CALLBACK_3;
     private Dispatcher CGLIB$CALLBACK_4;
     private MethodInterceptor CGLIB$CALLBACK_5;
     private MethodInterceptor CGLIB$CALLBACK_6;
     private static Object CGLIB$CALLBACK_FILTER;
     private static final Method CGLIB$doWork$0$Method;
     private static final MethodProxy CGLIB$doWork$0$Proxy;
     private static final Object[] CGLIB$emptyArgs;
     private static final Method CGLIB$equals$1$Method;
     private static final MethodProxy CGLIB$equals$1$Proxy;
     private static final Method CGLIB$toString$2$Method;
     private static final MethodProxy CGLIB$toString$2$Proxy;
     private static final Method CGLIB$hashCode$3$Method;
     private static final MethodProxy CGLIB$hashCode$3$Proxy;
     private static final Method CGLIB$clone$4$Method;
     private static final MethodProxy CGLIB$clone$4$Proxy;
 ​
     static void CGLIB$STATICHOOK1() {
         CGLIB$THREAD_CALLBACKS = new ThreadLocal();
         CGLIB$emptyArgs = new Object[0];
         Class var0 = Class.forName("com.lazy.snail.aop.Work$$EnhancerBySpringCGLIB$$3d7749bf");
         Class var1;
         CGLIB$doWork$0$Method = ReflectUtils.findMethods(new String[]{"doWork", "()V"}, (var1 = Class.forName("com.lazy.snail.aop.Work")).getDeclaredMethods())[0];
         CGLIB$doWork$0$Proxy = MethodProxy.create(var1, var0, "()V", "doWork", "CGLIB$doWork$0");
     }
 ​
     final void CGLIB$doWork$0() {
         super.doWork();
     }
 ​
     public final void doWork() {
         // 第一个CallBack,DynamicAdvisedInterceptor
         MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
         if (var10000 == null) {
             CGLIB$BIND_CALLBACKS(this);
             var10000 = this.CGLIB$CALLBACK_0;
         }
 ​
         if (var10000 != null) {
             // 第一个CallBack aopInterceptor intercept方法
             var10000.intercept(this, CGLIB$doWork$0$Method, CGLIB$emptyArgs, CGLIB$doWork$0$Proxy);
         } else {
             super.doWork();
         }
     }
 ​
     private static final void CGLIB$BIND_CALLBACKS(Object var0) {
         Work$$EnhancerBySpringCGLIB$$3d7749bf var1 = (Work$$EnhancerBySpringCGLIB$$3d7749bf)var0;
         if (!var1.CGLIB$BOUND) {
             var1.CGLIB$BOUND = true;
             Object var10000 = CGLIB$THREAD_CALLBACKS.get();
             if (var10000 == null) {
                 var10000 = CGLIB$STATIC_CALLBACKS;
                 if (var10000 == null) {
                     return;
                 }
             }
 ​
             Callback[] var10001 = (Callback[])var10000;
             var1.CGLIB$CALLBACK_6 = (MethodInterceptor)((Callback[])var10000)[6];
             var1.CGLIB$CALLBACK_5 = (MethodInterceptor)var10001[5];
             var1.CGLIB$CALLBACK_4 = (Dispatcher)var10001[4];
             var1.CGLIB$CALLBACK_3 = (Dispatcher)var10001[3];
             var1.CGLIB$CALLBACK_2 = (NoOp)var10001[2];
             var1.CGLIB$CALLBACK_1 = (MethodInterceptor)var10001[1];
             var1.CGLIB$CALLBACK_0 = (MethodInterceptor)var10001[0];
         }
 ​
     }
 ​
     public Callback getCallback(int var1) {
         CGLIB$BIND_CALLBACKS(this);
         Object var10000;
         switch (var1) {
             case 0:
                 var10000 = this.CGLIB$CALLBACK_0;
                 break;
             case 1:
                 var10000 = this.CGLIB$CALLBACK_1;
                 break;
             case 2:
                 var10000 = this.CGLIB$CALLBACK_2;
                 break;
             case 3:
                 var10000 = this.CGLIB$CALLBACK_3;
                 break;
             case 4:
                 var10000 = this.CGLIB$CALLBACK_4;
                 break;
             case 5:
                 var10000 = this.CGLIB$CALLBACK_5;
                 break;
             case 6:
                 var10000 = this.CGLIB$CALLBACK_6;
                 break;
             default:
                 var10000 = null;
         }
 ​
         return (Callback)var10000;
     }
 ​
     public void setCallback(int var1, Callback var2) {
         switch (var1) {
             case 0:
                 this.CGLIB$CALLBACK_0 = (MethodInterceptor)var2;
                 break;
             case 1:
                 this.CGLIB$CALLBACK_1 = (MethodInterceptor)var2;
                 break;
             case 2:
                 this.CGLIB$CALLBACK_2 = (NoOp)var2;
                 break;
             case 3:
                 this.CGLIB$CALLBACK_3 = (Dispatcher)var2;
                 break;
             case 4:
                 this.CGLIB$CALLBACK_4 = (Dispatcher)var2;
                 break;
             case 5:
                 this.CGLIB$CALLBACK_5 = (MethodInterceptor)var2;
                 break;
             case 6:
                 this.CGLIB$CALLBACK_6 = (MethodInterceptor)var2;
         }
 ​
     }
 ​
     public Callback[] getCallbacks() {
         CGLIB$BIND_CALLBACKS(this);
         return new Callback[]{this.CGLIB$CALLBACK_0, this.CGLIB$CALLBACK_1, this.CGLIB$CALLBACK_2, this.CGLIB$CALLBACK_3, this.CGLIB$CALLBACK_4, this.CGLIB$CALLBACK_5, this.CGLIB$CALLBACK_6};
     }
 ​
     public void setCallbacks(Callback[] var1) {
         this.CGLIB$CALLBACK_0 = (MethodInterceptor)var1[0];
         this.CGLIB$CALLBACK_1 = (MethodInterceptor)var1[1];
         this.CGLIB$CALLBACK_2 = (NoOp)var1[2];
         this.CGLIB$CALLBACK_3 = (Dispatcher)var1[3];
         this.CGLIB$CALLBACK_4 = (Dispatcher)var1[4];
         this.CGLIB$CALLBACK_5 = (MethodInterceptor)var1[5];
         this.CGLIB$CALLBACK_6 = (MethodInterceptor)var1[6];
     }
 ​
     static {
         CGLIB$STATICHOOK1();
     }
 }

2.2拦截入口

 // DynamicAdvisedInterceptor
 public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
         // 省略部分代码...
     
         // 从advised中获取拦截链
         // 将获取到ExposeInvocationInterceptor 和 MethodBeforeAdviceInterceptor
         List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
         Object retVal;
     
         // 省略部分代码...
     
         // 1.创建CglibMethodInvocation
        // 2.proceed
         retVal = new CglibMethodInvocation(proxy, target, method, args, targetClass, chain, methodProxy).proceed();
         retVal = processReturnType(proxy, target, method, retVal);
         return retVal;
     
         // 省略部分代码...
     }
 // CglibMethodInvocation
 public Object proceed() throws Throwable {
     // 省略部分代码...
     return super.proceed();
     // 省略部分代码...
 }
 // ReflectiveMethodInvocation
 public Object proceed() throws Throwable {
     // 下标从-1开始,提前递增
     if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
         return invokeJoinpoint();
     }
 ​
     Object interceptorOrInterceptionAdvice =
             this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
     return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
 }

2.3第一步ExposeInvocationInterceptor

 // ExposeInvocationInterceptor
 public Object invoke(MethodInvocation mi) throws Throwable {
     MethodInvocation oldInvocation = invocation.get();
     invocation.set(mi);
     try {
         return mi.proceed();
     }
     finally {
         invocation.set(oldInvocation);
     }
 }
 // CglibMethodInvocation
 public Object proceed() throws Throwable {
     return super.proceed();
 }
 // ReflectiveMethodInvocation
 public Object proceed() throws Throwable {
     // 0
     if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
         return invokeJoinpoint();
     }
 ​
     Object interceptorOrInterceptionAdvice =
             this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
     return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
 }

2.4第二步MethodBeforeAdviceInterceptor

 // MethodBeforeAdviceInterceptor
 public Object invoke(MethodInvocation mi) throws Throwable {
     // 切面中beforeWork逻辑 反射调用
     this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis());
     // CglibMethodInvocation.proceed
     return mi.proceed();
 }
 // CglibMethodInvocation
 public Object proceed() throws Throwable {
     return super.proceed();
 }
 // ReflectiveMethodInvocation
 public Object proceed() throws Throwable {
     // 1
     if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
         return invokeJoinpoint();
     }
 }
 ​
 protected Object invokeJoinpoint() throws Throwable {
     if (this.methodProxy != null) {
         try {
             return this.methodProxy.invoke(this.target, this.arguments);
         } catch (CodeGenerationException ex) {
             logFastClassGenerationFailure(this.method);
         }
     }
     return super.invokeJoinpoint();
 }
 // MethodProxy
 public Object invoke(Object obj, Object[] args) throws Throwable {
     init();
     FastClassInfo fci = fastClassInfo;
     // 反射调用Work的doWork方法
     // 这里FastClassInfo构建据说是为了提高反射的效率
     return fci.f1.invoke(fci.i1, obj, args);
 }

三、总结

1、代理类的创建

当 Spring 容器准备实例化目标类 Work 时,代理类的创建过程如下:

1.1 postProcessBeforeInstantiation()

  • 关键类AnnotationAwareAspectJAutoProxyCreator

  • 核心方法

    • postProcessBeforeInstantiation(Class<?> beanClass, String beanName)

      :在实例化 Bean 之前调用。

      • 功能:检查当前类是否需要代理,通常会调用 shouldSkip() 方法。
    • shouldSkip(Class<?> beanClass)

      :判断当前 Bean 是否应该跳过代理。

      • 如果返回 true,直接实例化目标类,不进行 AOP 代理。

1.2 findCandidateAdvisors()

  • 核心方法

    • findCandidateAdvisors()

      :用于查找与当前 Bean 相关的 Advisors(增强)。

      • 流程:此方法会调用 findEligibleAdvisors(),对所有注册的 Advisors 进行检查,匹配符合切点表达式的增强。

1.3 createProxy()

  • 核心类ProxyFactory

  • 核心方法

    • createProxy()

      • 功能:生成目标类的代理对象。

      • 流程

        • 如果目标类 Work 实现了接口,则创建 JDK 动态代理。
        • 如果没有实现接口,则创建 CGLIB 代理。
        • 在这里,会调用 getProxy() 方法来完成代理对象的生成。
    • getProxy(ClassLoader classLoader)

      • 功能:根据目标类和回调创建代理。

      • 关键过程

        • 设置 superClassWork.class,并指定回调(MethodInterceptor)。

2. 客户端调用代理对象

当客户端调用代理对象的方法时,执行过程如下:

2.1 调用代理方法

  • 客户端代码

     Work work = (Work) applicationContext.getBean("work");
     work.doWork(); // 代理对象的方法调用
    

2.2 invoke()

  • 核心类CglibAopProxyJdkDynamicAopProxy(取决于代理类型)

  • 核心方法

    • invoke(Object proxy, Method method, Object[] args)

      • 功能:拦截对目标方法的调用。

      • 流程

        • 检查当前方法是否在 Advisor 的切点范围内。
        • 如果在范围内,执行前置通知(如调用 beforeWork() 方法)。

2.3 前置通知与目标方法执行

  • MethodInterceptor

    • 核心方法

      • intercept(Object obj, Method method, Object[] args, MethodProxy proxy)

        • 功能:实现增强逻辑。

        • 流程

          • 在此方法内执行增强逻辑(如调用 B.b())。
          • 使用 proxy.invokeSuper(obj, args) 调用目标方法 doWork(),确保目标类的实际逻辑被执行。

小结

1.代理类的创建通过 AnnotationAwareAspectJAutoProxyCreator 实现,关键方法包括 postProcessBeforeInstantiation()findCandidateAdvisors()createProxy(),这些方法负责判断是否需要代理,并生成代理对象。

2.客户端调用代理对象时,CGLIB 或 JDK 代理的 invoke() 方法会拦截对目标方法的调用,并通过 MethodInterceptor 执行增强逻辑,最终调用目标方法。