关于java:Spring源码之AOP实现原理

38次阅读

共计 22843 个字符,预计需要花费 58 分钟才能阅读完成。

Spring 源码之 AOP 实现原理

@EnableAspectJAutoProxy

@EnableAspectJAutoProxy;外围从这个动手,AOP 整个性能要启作用, 就是靠这个, 退出它才有 AOP

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
// 导入 AspectJAutoProxyRegistrar
@Import(AspectJAutoProxyRegistrar.class)
public @interface EnableAspectJAutoProxy {

    /**
     * Indicate whether subclass-based (CGLIB) proxies are to be created as opposed
     * to standard Java interface-based proxies. The default is {@code false}.
     */
  // proxyTargetClass 属性,默认 false,采纳 JDK 动静代理织入加强 (实现接口的形式);如果设为 true,则采纳 CGLIB 动静代理织入加强
    boolean proxyTargetClass() default false;

    /**
     * Indicate that the proxy should be exposed by the AOP framework as a {@code ThreadLocal}
     * for retrieval via the {@link org.springframework.aop.framework.AopContext} class.
     * Off by default, i.e. no guarantees that {@code AopContext} access will work.
     * @since 4.3.1
     */
  // 通过 aop 框架裸露该代理对象,aopContext 可能拜访
    boolean exposeProxy() default false;}

AspectJAutoProxyRegistrar

/**
 * Registers an {@link org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator
 * AnnotationAwareAspectJAutoProxyCreator} against the current {@link BeanDefinitionRegistry}
 * as appropriate based on a given @{@link EnableAspectJAutoProxy} annotation.
 *
 * @author Chris Beams
 * @author Juergen Hoeller
 * @since 3.1
 * @see EnableAspectJAutoProxy
 */
// 实现 ImportBeanDefinitionRegistrar 接口
class AspectJAutoProxyRegistrar implements ImportBeanDefinitionRegistrar {

    /**
     * Register, escalate, and configure the AspectJ auto proxy creator based on the value
     * of the @{@link EnableAspectJAutoProxy#proxyTargetClass()} attribute on the importing
     * {@code @Configuration} class.
     */
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {

    // 注册 AnnotationAwareAspectJAutoProxyCreator 组件
        AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(registry);

        AnnotationAttributes enableAspectJAutoProxy =
                AnnotationConfigUtils.attributesFor(importingClassMetadata, EnableAspectJAutoProxy.class);
        if (enableAspectJAutoProxy != null) {if (enableAspectJAutoProxy.getBoolean("proxyTargetClass")) {AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
            }
            if (enableAspectJAutoProxy.getBoolean("exposeProxy")) {AopConfigUtils.forceAutoProxyCreatorToExposeProxy(registry);
            }
        }
    }

}

registerAspectJAnnotationAutoProxyCreatorIfNecessary

    @Nullable
    public static BeanDefinition registerAspectJAnnotationAutoProxyCreatorIfNecessary(BeanDefinitionRegistry registry) {return registerAspectJAnnotationAutoProxyCreatorIfNecessary(registry, null);
    }


    @Nullable
    public static BeanDefinition registerAspectJAnnotationAutoProxyCreatorIfNecessary(BeanDefinitionRegistry registry, @Nullable Object source) {return registerOrEscalateApcAsRequired(AnnotationAwareAspectJAutoProxyCreator.class, registry, source);
    }

    @Nullable
    private static BeanDefinition registerOrEscalateApcAsRequired(Class<?> cls, BeanDefinitionRegistry registry, @Nullable Object source) {Assert.notNull(registry, "BeanDefinitionRegistry must not be null");

    // 如果容器中 bean 曾经有了
        if (registry.containsBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME)) {BeanDefinition apcDefinition = registry.getBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME);
            if (!cls.getName().equals(apcDefinition.getBeanClassName())) {int currentPriority = findPriorityForClass(apcDefinition.getBeanClassName());
                int requiredPriority = findPriorityForClass(cls);
                if (currentPriority < requiredPriority) {apcDefinition.setBeanClassName(cls.getName());
                }
            }
            return null;
        }

        RootBeanDefinition beanDefinition = new RootBeanDefinition(cls);
        beanDefinition.setSource(source);
        beanDefinition.getPropertyValues().add("order", Ordered.HIGHEST_PRECEDENCE);
        beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
        registry.registerBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME, beanDefinition);
        return beanDefinition;
    }

IOC 容器中注入了一个 internalAutoProxyCreator=AnnotationAwareAspectJAutoProxyCreator 的 bean, 到此能够得出结论,@EnableAspectJAutoProxy 给容器中注册一个 AnnotationAwareAspectJAutoProxyCreator。

三、AnnotationAwareAspectJAutoProxyCreator 创立过程

AnnotationAwareAspectJAutoProxyCreator

重点钻研 AnnotationAwareAspectJAutoProxyCreator 组件 (ASPECT 主动代理创立器)

AnnotationAwareAspectJAutoProxyCreator 类关系图如下, 继承关系:

AnnotationAwareAspectJAutoProxyCreator:

\* AnnotationAwareAspectJAutoProxyCreator

\* ->AspectJAwareAdvisorAutoProxyCreator

\* ->AbstractAdvisorAutoProxyCreator

\* ->AbstractAutoProxyCreator

\* implements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware

\* 关注后置处理器(在 bean 初始化实现前后做事件)、主动拆卸 BeanFactory

SmartInstantiationAwareBeanPostProcessor: bean 的后置处理器(在 bean 初始化实现前后做事件)

BeanFactoryAware 能把 beanFacotry bean 工厂传进来

创立和注册 AnnotationAwareAspectJAutoProxyCreator

1)、传入配置类,创立 ioc 容器
          2)、注册配置类,调用 refresh()刷新容器;3)、registerBeanPostProcessors(beanFactory); 注册 bean 的后置处理器来不便拦挡 bean 的创立;1)、先获取 ioc 容器曾经定义了的须要创建对象的所有 BeanPostProcessor
              2)、给容器中加别的 BeanPostProcessor
              3)、优先注册实现了 PriorityOrdered 接口的 BeanPostProcessor;4)、再给容器中注册实现了 Ordered 接口的 BeanPostProcessor;5)、注册没实现优先级接口的 BeanPostProcessor;6)、注册 BeanPostProcessor,实际上就是创立 BeanPostProcessor 对象,保留在容器中;创立 internalAutoProxyCreator 的 BeanPostProcessor【AnnotationAwareAspectJAutoProxyCreator】1)、创立 Bean 的实例
                  2)、populateBean;给 bean 的各种属性赋值
                  3)、initializeBean:初始化 bean;1)、invokeAwareMethods():解决 Aware 接口的办法回调
                          2)、applyBeanPostProcessorsBeforeInitialization():利用后置处理器的 postProcessBeforeInitialization()3)、invokeInitMethods();执行自定义的初始化办法
                          4)、applyBeanPostProcessorsAfterInitialization();执行后置处理器的 postProcessAfterInitialization();4)、BeanPostProcessor(AnnotationAwareAspectJAutoProxyCreator) 创立胜利;--》aspectJAdvisorsBuilder
              7)、把 BeanPostProcessor 注册到 BeanFactory 中;beanFactory.addBeanPostProcessor(postProcessor);  

registerBeanPostProcessors:

    /**
     * Instantiate and register all BeanPostProcessor beans,
     * respecting explicit order if given.
     * <p>Must be called before any instantiation of application beans.
     */
    protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
    }

PostProcessorRegistrationDelegate.registerBeanPostProcessors:

    public static void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);

        // Register BeanPostProcessorChecker that logs an info message when
        // a bean is created during BeanPostProcessor instantiation, i.e. when
        // a bean is not eligible for getting processed by all BeanPostProcessors.
        int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
        beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

        // Separate between BeanPostProcessors that implement PriorityOrdered,
        // Ordered, and the rest.
        List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
        List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
        List<String> orderedPostProcessorNames = new ArrayList<>();
        List<String> nonOrderedPostProcessorNames = new ArrayList<>();
        for (String ppName : postProcessorNames) {if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
                priorityOrderedPostProcessors.add(pp);
                if (pp instanceof MergedBeanDefinitionPostProcessor) {internalPostProcessors.add(pp);
                }
            }
            else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {orderedPostProcessorNames.add(ppName);
            }
            else {nonOrderedPostProcessorNames.add(ppName);
            }
        }

        // First, register the BeanPostProcessors that implement PriorityOrdered.
        sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
        registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

        // Next, register the BeanPostProcessors that implement Ordered.
        List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>();
        for (String ppName : orderedPostProcessorNames) {BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
            orderedPostProcessors.add(pp);
            if (pp instanceof MergedBeanDefinitionPostProcessor) {internalPostProcessors.add(pp);
            }
        }
        sortPostProcessors(orderedPostProcessors, beanFactory);
        registerBeanPostProcessors(beanFactory, orderedPostProcessors);

        // Now, register all regular BeanPostProcessors.
        List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
        for (String ppName : nonOrderedPostProcessorNames) {BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
            nonOrderedPostProcessors.add(pp);
            if (pp instanceof MergedBeanDefinitionPostProcessor) {internalPostProcessors.add(pp);
            }
        }
        registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);

        // Finally, re-register all internal BeanPostProcessors.
        sortPostProcessors(internalPostProcessors, beanFactory);
        registerBeanPostProcessors(beanFactory, internalPostProcessors);

        // Re-register post-processor for detecting inner beans as ApplicationListeners,
        // moving it to the end of the processor chain (for picking up proxies etc).
        beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
    }

AnnotationAwareAspectJAutoProxyCreator 的执行机会

之前剖析到 AnnotationAwareAspectJAutoProxyCreator 是一个后置处理器,能够猜想它在其余 bean 的初始化前后进行了非凡解决。

4)、finishBeanFactoryInitialization(beanFactory); 实现 BeanFactory 初始化工作;创立剩下的单实例 bean
              1)、遍历获取容器中所有的 Bean,顺次创建对象 getBean(beanName);
                  getBean->doGetBean()->getSingleton()->
              2)、创立 bean【AnnotationAwareAspectJAutoProxyCreator 在所有 bean 创立之前会有一个拦挡,InstantiationAwareBeanPostProcessor,会调用 postProcessBeforeInstantiation()】1)、先从缓存中获取以后 bean,如果能获取到,阐明 bean 是之前被创立过的,间接应用,否则再创立;只有创立好的 Bean 都会被缓存起来
                  2)、createBean(); 创立 bean;AnnotationAwareAspectJAutoProxyCreator 会在任何 bean 创立之前先尝试返回 bean 的实例【BeanPostProcessor 是在 Bean 对象创立实现初始化前后调用的】【InstantiationAwareBeanPostProcessor 是在创立 Bean 实例之前先尝试用后置处理器返回对象的】1)、resolveBeforeInstantiation(beanName, mbdToUse); 解析 BeforeInstantiation
                          心愿后置处理器在此能返回一个代理对象;如果能返回代理对象就应用,如果不能就持续
                          1)、后置处理器先尝试返回对象;bean = applyBeanPostProcessorsBeforeInstantiation():拿到所有后置处理器,如果是 InstantiationAwareBeanPostProcessor;
                                  就执行 postProcessBeforeInstantiation
                              if (bean != null) {bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
                            }
  
                      2)、doCreateBean(beanName, mbdToUse, args); 真正的去创立一个 bean 实例;和 3.6 流程一样;3)、

*AnnotationAwareAspectJAutoProxyCreator 会在任何 bean 创立之前先尝试返回 bean 的实例

【BeanPostProcessor 是在 Bean 对象创立实现初始化前后调用的】【InstantiationAwareBeanPostProcessor 是在创立 Bean 实例之前先尝试用后置处理器返回对象的】*

AbstractAutowireCapableBeanFactory#createBean

        try {
            // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
            Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
            if (bean != null) {return bean;}
        }
        catch (Throwable ex) {throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
                    "BeanPostProcessor before instantiation of bean failed", ex);
        }
    @Nullable
    protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
        Object bean = null;
        if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
            // Make sure bean class is actually resolved at this point.
            if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {Class<?> targetType = determineTargetType(beanName, mbd);
                if (targetType != null) {bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
                    if (bean != null) {bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
                    }
                }
            }
            mbd.beforeInstantiationResolved = (bean != null);
        }
        return bean;
    }
    @Nullable
    protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) {for (BeanPostProcessor bp : getBeanPostProcessors()) {if (bp instanceof InstantiationAwareBeanPostProcessor) {InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
                if (result != null) {return result;}
            }
        }
        return null;
    }

AbstractAutoProxyCreator#postProcessBeforeInstantiation

    @Override
    public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) {Object cacheKey = getCacheKey(beanClass, beanName);

        if (!StringUtils.hasLength(beanName) || !this.targetSourcedBeans.contains(beanName)) {if (this.advisedBeans.containsKey(cacheKey)) {return null;}
            if (isInfrastructureClass(beanClass) || shouldSkip(beanClass, beanName)) {this.advisedBeans.put(cacheKey, Boolean.FALSE);
                return null;
            }
        }

        // Create proxy here if we have a custom TargetSource.
        // Suppresses unnecessary default instantiation of the target bean:
        // The TargetSource will handle target instances in a custom fashion.
        TargetSource targetSource = getCustomTargetSource(beanClass, beanName);
        if (targetSource != null) {if (StringUtils.hasLength(beanName)) {this.targetSourcedBeans.add(beanName);
            }
            Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);
            Object proxy = createProxy(beanClass, beanName, specificInterceptors, targetSource);
            this.proxyTypes.put(cacheKey, proxy.getClass());
            return proxy;
        }

        return null;
    }

创立 AOP 代理

AbstractAutoProxyCreator#postProcessBeforeInstantiation 办法外部会进行一系列的判断,判断以后 bean 是否在 advisedBeans 中(保留了所有须要加强 bean)、判断以后 bean 是否是根底类型的 Advice、Pointcut、Advisor、AopInfrastructureBean、判断是否是切面(是否实现了注解 @Aspect)、判断是否须要跳过等。

在判断的过程中会拿到加强 bean 的相干的告诉办法,并通过这些切面进行逻辑判断。

执行完 postProcessBeforeInstantiation 办法进行告诉办法的判断后,执行 postProcessAfterInitialization 办法。

AbstractAutoProxyCreator#postProcessAfterInitialization

    /**
     * Create a proxy with the configured interceptors if the bean is
     * identified as one to proxy by the subclass.
     * @see #getAdvicesAndAdvisorsForBean
     */
    @Override
    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) {if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {return bean;}
        if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {return bean;}
        if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {this.advisedBeans.put(cacheKey, Boolean.FALSE);
            return bean;
        }

        // Create proxy if we have advice.
        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;
    }

创立代理对象的过程,发现在创立之前首先会依据切入点表达式对增强器进行一一匹配,最终拿到所有的增强器

    /**
     * Create an AOP proxy for the given bean.
     * @param beanClass the class of the bean
     * @param beanName the name of the bean
     * @param specificInterceptors the set of interceptors that is
     * specific to this bean (may be empty, but not null)
     * @param targetSource the TargetSource for the proxy,
     * already pre-configured to access the bean
     * @return the AOP proxy for the bean
     * @see #buildAdvisors
     */
    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()) {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);
        }

        return proxyFactory.getProxy(getProxyClassLoader());
    }
    /**
     * Create a new proxy according to the settings in this factory.
     * <p>Can be called repeatedly. Effect will vary if we've added
     * or removed interfaces. Can add and remove interceptors.
     * <p>Uses the given class loader (if necessary for proxy creation).
     * @param classLoader the class loader to create the proxy with
     * (or {@code null} for the low-level proxy facility's default)
     * @return the proxy object
     */
    public Object getProxy(@Nullable ClassLoader classLoader) {return createAopProxy().getProxy(classLoader);
    }

创立代理对象过程中,会先创立一个代理工厂,获取到所有的增强器(告诉办法),将这些增强器和指标类注入代理工厂,再用代理工厂创建对象。

代理工厂会抉择 JdkDynamicAopProxy 或者 CglibAopProxy,次要通过是否接口和是否配置 cglib 代理来抉择。

获取拦截器链

剖析指标办法被拦挡并执行的过程。

 指标办法执行;容器中保留了组件的代理对象(cglib 加强后的对象),这个对象外面保留了详细信息(比方增强器,指标对象,xxx);1)、CglibAopProxy.intercept(); 拦挡指标办法的执行
         2)、依据 ProxyFactory 对象获取将要执行的指标办法拦截器链;List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
             1)、List<Object> interceptorList 保留所有拦截器 5
                 一个默认的 ExposeInvocationInterceptor 和 4 个增强器;2)、遍历所有的增强器,将其转为 Interceptor;registry.getInterceptors(advisor);
             3)、将增强器转为 List<MethodInterceptor>;如果是 MethodInterceptor,间接退出到汇合中
                 如果不是,应用 AdvisorAdapter 将增强器转为 MethodInterceptor;转换实现返回 MethodInterceptor 数组;3)、如果没有拦截器链,间接执行指标办法;        拦截器链(每一个告诉办法又被包装为办法拦截器,利用 MethodInterceptor 机制)4)、如果有拦截器链,把须要执行的指标对象,指标办法,拦截器链等信息传入创立一个 CglibMethodInvocation 对象,并调用 Object retVal =  mi.proceed();5)、拦截器链的触发过程;        1)、如果没有拦截器执行执行指标办法,或者拦截器的索引和拦截器数组 - 1 大小一样(指定到了最初一个拦截器)执行指标办法;2)、链式获取每一个拦截器,拦截器执行 invoke 办法,每一个拦截器期待下一个拦截器执行实现返回当前再来执行;拦截器链的机制,保障告诉办法与指标办法的执行程序;

CglibAopProxy:

/**
     * General purpose AOP callback. Used when the target is dynamic or when the
     * proxy is not frozen.
     */
    private static class DynamicAdvisedInterceptor implements MethodInterceptor, Serializable {

        private final AdvisedSupport advised;

        public DynamicAdvisedInterceptor(AdvisedSupport advised) {this.advised = advised;}

        @Override
        @Nullable
        public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
            Object oldProxy = null;
            boolean setProxyContext = false;
            Object target = null;
            TargetSource targetSource = this.advised.getTargetSource();
            try {if (this.advised.exposeProxy) {
                    // Make invocation available if necessary.
                    oldProxy = AopContext.setCurrentProxy(proxy);
                    setProxyContext = true;
                }
                // Get as late as possible to minimize the time we "own" the target, in case it comes from a pool...
                target = targetSource.getTarget();
                Class<?> targetClass = (target != null ? target.getClass() : null);
                List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
                Object retVal;
                // Check whether we only have one InvokerInterceptor: that is,
                // no real advice, but just reflective invocation of the target.
                if (chain.isEmpty() && Modifier.isPublic(method.getModifiers())) {
                    // We can skip creating a MethodInvocation: just invoke the target directly.
                    // Note that the final invoker must be an InvokerInterceptor, so we know
                    // it does nothing but a reflective operation on the target, and no hot
                    // swapping or fancy proxying.
                    Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
                    retVal = methodProxy.invoke(target, argsToUse);
                }
                else {
                    // We need to create a method invocation...
          // 办法调用
                    retVal = new CglibMethodInvocation(proxy, target, method, args, targetClass, chain, methodProxy).proceed();}
                retVal = processReturnType(proxy, target, method, retVal);
                return retVal;
            }
            finally {if (target != null && !targetSource.isStatic()) {targetSource.releaseTarget(target);
                }
                if (setProxyContext) {
                    // Restore old proxy.
                    AopContext.setCurrentProxy(oldProxy);
                }
            }
        }

        @Override
        public boolean equals(Object other) {
            return (this == other ||
                    (other instanceof DynamicAdvisedInterceptor &&
                            this.advised.equals(((DynamicAdvisedInterceptor) other).advised)));
        }

        /**
         * CGLIB uses this to drive proxy creation.
         */
        @Override
        public int hashCode() {return this.advised.hashCode();
        }
    }
public class DefaultAdvisorChainFactory implements AdvisorChainFactory, Serializable {

    @Override
    public List<Object> getInterceptorsAndDynamicInterceptionAdvice(Advised config, Method method, @Nullable Class<?> targetClass) {

        // This is somewhat tricky... We have to process introductions first,
        // but we need to preserve order in the ultimate list.
        AdvisorAdapterRegistry registry = GlobalAdvisorAdapterRegistry.getInstance();
        Advisor[] advisors = config.getAdvisors();
        List<Object> interceptorList = new ArrayList<>(advisors.length);
        Class<?> actualClass = (targetClass != null ? targetClass : method.getDeclaringClass());
        Boolean hasIntroductions = null;

        for (Advisor advisor : advisors) {if (advisor instanceof PointcutAdvisor) {
                // Add it conditionally.
                PointcutAdvisor pointcutAdvisor = (PointcutAdvisor) advisor;
                if (config.isPreFiltered() || pointcutAdvisor.getPointcut().getClassFilter().matches(actualClass)) {MethodMatcher mm = pointcutAdvisor.getPointcut().getMethodMatcher();
                    boolean match;
                    if (mm instanceof IntroductionAwareMethodMatcher) {if (hasIntroductions == null) {hasIntroductions = hasMatchingIntroductions(advisors, actualClass);
                        }
                        match = ((IntroductionAwareMethodMatcher) mm).matches(method, actualClass, hasIntroductions);
                    }
                    else {match = mm.matches(method, actualClass);
                    }
                    if (match) {MethodInterceptor[] interceptors = registry.getInterceptors(advisor);
                        if (mm.isRuntime()) {// Creating a new object instance in the getInterceptors() method
                            // isn't a problem as we normally cache created chains.
                            for (MethodInterceptor interceptor : interceptors) {interceptorList.add(new InterceptorAndDynamicMethodMatcher(interceptor, mm));
                            }
                        }
                        else {interceptorList.addAll(Arrays.asList(interceptors));
                        }
                    }
                }
            }
            else if (advisor instanceof IntroductionAdvisor) {IntroductionAdvisor ia = (IntroductionAdvisor) advisor;
                if (config.isPreFiltered() || ia.getClassFilter().matches(actualClass)) {Interceptor[] interceptors = registry.getInterceptors(advisor);
                    interceptorList.addAll(Arrays.asList(interceptors));
                }
            }
            else {Interceptor[] interceptors = registry.getInterceptors(advisor);
                interceptorList.addAll(Arrays.asList(interceptors));
            }
        }

        return interceptorList;
    }
}
    @Override
    public MethodInterceptor[] getInterceptors(Advisor advisor) throws UnknownAdviceTypeException {List<MethodInterceptor> interceptors = new ArrayList<>(3);
        Advice advice = advisor.getAdvice();
        if (advice instanceof MethodInterceptor) {interceptors.add((MethodInterceptor) advice);
        }
        for (AdvisorAdapter adapter : this.adapters) {if (adapter.supportsAdvice(advice)) {interceptors.add(adapter.getInterceptor(advisor));
            }
        }
        if (interceptors.isEmpty()) {throw new UnknownAdviceTypeException(advisor.getAdvice());
        }
        return interceptors.toArray(new MethodInterceptor[0]);
    }

通过 registry.getInterceptors(advisor) 办法获取所有的增强器,并将增强器转为 List<MethodInterceptor>,最终返回。

// 将拦截器链和指标对象等传入 methodInvocation,并调用 proceed() 办法。该办法执行也是拦截器的触发过程,也是指标办法的次要执行过程。@Override
    @Nullable
    public Object proceed() throws Throwable {
        // We start with an index of -1 and increment early.
        if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {return invokeJoinpoint();
        }

        Object interceptorOrInterceptionAdvice =
                this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
        if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
            // Evaluate dynamic method matcher here: static part will already have
            // been evaluated and found to match.
            InterceptorAndDynamicMethodMatcher dm =
                    (InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;
            Class<?> targetClass = (this.targetClass != null ? this.targetClass : this.method.getDeclaringClass());
            if (dm.methodMatcher.matches(this.method, targetClass, this.arguments)) {return dm.interceptor.invoke(this);
            }
            else {
                // Dynamic matching failed.
                // Skip this interceptor and invoke the next in the chain.
                return proceed();}
        }
        else {
            // It's an interceptor, so we just invoke it: The pointcut will have
            // been evaluated statically before this object was constructed.
            return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
        }
    }

小结

1)、@EnableAspectJAutoProxy 开启 AOP 性能
 2)、@EnableAspectJAutoProxy 会给容器中注册一个组件 AnnotationAwareAspectJAutoProxyCreator
 3)、AnnotationAwareAspectJAutoProxyCreator 是一个后置处理器;4)、容器的创立流程:1)、registerBeanPostProcessors()注册后置处理器;创立 AnnotationAwareAspectJAutoProxyCreator 对象
        2)、finishBeanFactoryInitialization()初始化剩下的单实例 bean
            1)、创立业务逻辑组件和切面组件
            2)、AnnotationAwareAspectJAutoProxyCreator 拦挡组件的创立过程
            3)、组件创立完之后,判断组件是否须要加强
                     是:切面的告诉办法,包装成增强器(Advisor); 给业务逻辑组件创立一个代理对象(cglib);5)、执行指标办法:1)、代理对象执行指标办法
        2)、CglibAopProxy.intercept();1)、失去指标办法的拦截器链(增强器包装成拦截器 MethodInterceptor)2)、利用拦截器的链式机制,顺次进入每一个拦截器进行执行;3)、成果:失常执行:前置告诉 -》指标办法 -》后置告诉 -》返回告诉
                      出现异常:前置告诉 -》指标办法 -》后置告诉 -》异样告诉 

正文完
 0