Spring AOP源码详细解析

一 . 以下是bean的初始化过程: 

注意: 先明白beanPostProcessor的作用,才能够明白aop的加载时机

在bean实例化完成之前和完成之后分别会自动BeanPostProcessor接口的postProcessBeforeInitialization和postProcessAfterInitialization方法。

 

二: 介绍一些Spring Aop中一些核心类,大致分为三类:

    advisorCreator,继承 spring ioc的扩展接口 beanPostProcessor,主要用来扫描获取 advisor。

    beanPostProcessor作用: Spring容器中完成bean实例化、配置以及其他初始化方法前后要添加一些自己逻辑处理。

                                                 我们需要定义一个或多个BeanPostProcessor接口实现类,然后注册到Spring IoC容器中。
    advisor:顾问的意思,封装了spring aop中的切点和通知。 就是我们常用的@Aspect 注解标记得类
    advice:通知,也就是aop中增强的方法。

advisorCreator:

  

 

AbstractAutoProxyCreator:Spring 为Spring AOP 模块暴露的可扩展抽象类,也是 AOP 中最核心的抽象类。Nepxion Matrix 框架便是基于此类对AOP进行扩展和增强。

BeanNameAutoProxyCreator:根据指定名称创建代理对象(阿里大名鼎鼎的连接池框架druid也基于此类做了扩展)。通过设置 advisor,可以对指定的 beanName 进行代理。支持模糊匹配。

AbstractAdvisorAutoProxyCreator:功能比较强大,默认扫描所有Advisor的实现类。相对于根据Bean名称匹配,该类更加灵活。动态的匹配每一个类,判断是否可以被代理,并寻找合适的增强类,以及生成代理类。

DefaultAdvisorAutoProxyCreator:AbstractAdvisorAutoProxyCreator的默认实现类。可以单独使用,在框架中使用AOP,尽量不要手动创建此对象。

AspectJAwareAdvisorAutoProxyCreator:Aspectj的实现方式,也是Spring Aop中最常用的实现方式,如果用注解方式,则用其子类AnnotationAwareAspectJAutoProxyCreator。

AnnotationAwareAspectJAutoProxyCreator:目前最常用的AOP使用方式。spring aop 开启注解方式之后,该类会扫描所有@Aspect()注释的类,生成对应的advisor。目前SpringBoot框架中默认支持的方式,自动配置。
 

     图片来自于: https://www.cnblogs.com/yuxiang1/archive/2018/06/19/9199730.html

 

三. spring实现AOP思路:

      1: 创建AnnotationAwareAspectJAutoProxyCreator对象
      2: 扫描容器中的切面,创建PointcutAdvisor对象
      3: 生成代理类

 

四 .介绍AbstractAutoProxyCreator中判断是否生成代理类以及

       创建PointcutAdvisor对象的过程:

可以看到在AbstractAutoProxyCreator类中的上层接口实现了BeanPostProcessor接口,

对于下面两个方法, 重写的第一个方法,其主要目的在于如果用户使用了自定义的TargetSource对象,则直接使用该对象生成目标对象,而不会使用Spring的默认逻辑生成目标对象,并且这里会判断各个切面逻辑是否可以应用到当前bean上,如果可以,则直接应用,也就是说TargetSource为使用者在Aop中提供了一个自定义生成目标bean逻辑的方式,并且会应用相应的切面逻辑。对于第二个方法,其主要作用在于Spring生成某个bean之后,将相关的切面逻辑应用到该bean上,

了解细致的TargetSource原理请参考: https://blog.csdn.net/zxfryp909012366/article/details/82881659

1. 以下是bean实例化之后, 初始化之前操作postProcessBeforeInstantiation

 在AbstractAutoProxyCreator类中实现BeanPostProcessor中的下面方法中:

 
  1. @Override

  2. public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {

  3. Object cacheKey = getCacheKey(beanClass, beanName);

  4.  
  5. if (!StringUtils.hasLength(beanName) || !this.targetSourcedBeans.contains(beanName)) {

  6. //advisedBeans用于存储不可代理的bean,如果包含直接返回

  7. if (this.advisedBeans.containsKey(cacheKey)) {

  8. return null;

  9. }

  10. //判断当前bean是否可以被代理,然后存入advisedBeans

  11. if (isInfrastructureClass(beanClass) || shouldSkip(beanClass, beanName)) {

  12. this.advisedBeans.put(cacheKey, Boolean.FALSE);

  13. return null;

  14. }

  15. }

  16.  
  17. // Create proxy here if we have a custom TargetSource.

  18. // Suppresses unnecessary default instantiation of the target bean:

  19. // The TargetSource will handle target instances in a custom fashion.

  20. //获取封装当前bean的TargetSource对象,如果不存在,则直接退出当前方法,否则从TargetSource

  21. // 中获取当前bean对象,并且判断是否需要将切面逻辑应用在当前bean上。

  22. TargetSource targetSource = getCustomTargetSource(beanClass, beanName);

  23. if (targetSource != null) {

  24. if (StringUtils.hasLength(beanName)) {

  25. this.targetSourcedBeans.add(beanName);

  26. }

  27. // 获取能够应用当前bean的切面逻辑

  28. Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);

  29. Object proxy = createProxy(beanClass, beanName, specificInterceptors, targetSource);

  30.  
  31. // 对生成的代理对象进行缓存

  32. this.proxyTypes.put(cacheKey, proxy.getClass());

  33. //如果最终可以获得代理类,则返回代理类,直接执行实例化后置通知方法

  34. return proxy;

  35. }

  36.  
  37. return null;

  38. }

 

================================================================================================

2. 以下是bean初始完成之后创建代理对象过程:postProcessAfterInitialization

在AbstractAutoProxyCreator类中实现BeanPostProcessor中的下面方法中:

 
  1. public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {

  2. if (bean != null) {

  3. //缓存键:1.beanName不为空的话,使用beanName(FactoryBean会在见面加上"&")

  4. //2.如果beanName为空,使用Class对象作为缓存的key

  5. Object cacheKey = getCacheKey(bean.getClass(), beanName);

  6. if (!this.earlyProxyReferences.contains(cacheKey)) {

  7. //如果条件符合,则为bean生成代理对象

  8. return wrapIfNecessary(bean, beanName, cacheKey);

  9. }

  10. }

  11. return bean;

  12. }

 wrapIfNecessary

   代码流程:

   1.  如果已经处理过,且该bean没有被代理过,则直接返回该bean
   2.如果该bean是内部基础设置类Class 或 配置了该bean不需要代理,则直接返回bean(返回前标记该bean已被处理过)
   3.获取所有适合该bean的增强Advisor
    如果增强不为null,则为该bean创建代理对象,并返回结果
    标记该bean已经被处理过

 
  1. protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {

  2. //如果已经处理过(targetSourcedBeans存放已经增强过的bean)

  3. if (beanName != null && this.targetSourcedBeans.contains(beanName)) {

  4. return bean;

  5. }

  6. //advisedBeans的key为cacheKey,value为boolean类型,表示是否进行过代理

  7. //已经处理过的bean,不需要再次进行处理,节省时间

  8. if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {

  9. return bean;

  10. }

  11. //是否是内部基础设置类Class || 配置了指定bean不需要代理,如果是的话,直接缓存。

  12. if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {

  13. this.advisedBeans.put(cacheKey, Boolean.FALSE);

  14. return bean;

  15. }

  16.  
  17. // 获取当前对象所有适用的Advisor.加入当前对象是orderController,那么找到所有切点是他的对应的@Aspect注解的类

  18. Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);

  19. //如果获取的增强不为null,则为该bean创建代理(DO_NOT_PROXY=null)

  20. if (specificInterceptors != DO_NOT_PROXY) {

  21. this.advisedBeans.put(cacheKey, Boolean.TRUE);

  22. //创建代理对象时候会用到是否进行JDK代理或者CGLIB代理

  23. Object proxy = createProxy(

  24. bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));

  25. this.proxyTypes.put(cacheKey, proxy.getClass());

  26. return proxy;

  27. }

  28. //标记该cacheKey已经被处理过

  29. this.advisedBeans.put(cacheKey, Boolean.FALSE);

  30. return bean;

  31. }

 

AspectJAwareAdvisorAutoProxyCreator的实现wrapIfNecessary方法中判断是否为基础类的方法:

 
  1. protected boolean isInfrastructureClass(Class<?> beanClass) {

  2. //如果bean继承自Advice、Pointcut、Advisor、AopInfrastructureBean

  3. boolean retVal = Advice.class.isAssignableFrom(beanClass) ||

  4. Pointcut.class.isAssignableFrom(beanClass) ||

  5. Advisor.class.isAssignableFrom(beanClass) ||

  6. AopInfrastructureBean.class.isAssignableFrom(beanClass);

  7. if (retVal && logger.isTraceEnabled()) {

  8. logger.trace("Did not attempt to auto-proxy infrastructure class [" + beanClass.getName() + "]");

  9. }

  10. return retVal;

  11. }

从上面代码可以看出,继承自Advice、Pointcut、Advisor、AopInfrastructureBean无法被增强

AnnotationAwareAspectJAutoProxyCreator 继承了AspectJAwareAdvisorAutoProxyCreator 类 调用父类方法时候

  在isInfrastructureClass时候,同时加了isAspect方法实现:

 
  1. public boolean isAspect(Class<?> clazz) {

  2. //如果bean带有@Aspect注解,或被Ajc(AspectJ编译器)编译

  3. return (hasAspectAnnotation(clazz) && !compiledByAjc(clazz));

  4. }

综上,如果一个bean继承自Advice、Pointcut、Advisor、AopInfrastructureBean 或者 带有@Aspect注解,或被Ajc(AspectJ编译器)编译都会被认定为内部基础设置类

在AnnotationUtils类中的findAnnotation方法中,判断这个bean上的注解类型是不是@Aspect

   以上②逻辑原文: https://blog.csdn.net/finalcola/article/details/82108745

 同时AspectJAwareAdvisorAutoProxyCreator的实现wrapIfNecessary方法中判断是否要进行代理的方法getAdvicesAndAdvisorsForBean同时会调用

findEligibleAdvisors处理两件事:

  • findCandidateAdvisors找到Spring中所有的Advisor.
  • findAdvisorsThatCanApply过滤出适合当前对象的advisors
 
  1. protected List<Advisor> findEligibleAdvisors(Class<?> beanClass, String beanName) {

  2.  
  3. //找到Spring中Advisor的实现类(findCandidateAdvisors)

  4. //将所有拥有@Aspect注解的类转换为advisors(aspectJAdvisorsBuilder.buildAspectJAdvisors)

  5. List<Advisor> candidateAdvisors = findCandidateAdvisors();

  6.  
  7. /* findAdvisorsThatCanApply

  8. 找到当前对象适合的所有Advisor。整个过程比较简单:

  9. 遍历所有的advisor。

  10. 查看当前advisor的pointCut是否适用于当前对象,如果是,进入候选队列,否则跳过。*/

  11.  
  12. List<Advisor> eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);

  13. //添加一个默认的advisor,执行时用到。

  14. extendAdvisors(eligibleAdvisors);

  15. if (!eligibleAdvisors.isEmpty()) {

  16. eligibleAdvisors = sortAdvisors(eligibleAdvisors);

  17. }

  18. return eligibleAdvisors;

  19. }

 

 findCandidateAdvisors:

 
  1. protected List<Advisor> findCandidateAdvisors() {

  2. // Add all the Spring advisors found according to superclass rules.

  3. List<Advisor> advisors = super.findCandidateAdvisors();

  4. // Build Advisors for all AspectJ aspects in the bean factory.

  5. advisors.addAll(this.aspectJAdvisorsBuilder.buildAspectJAdvisors());

  6. return advisors;

  7. }

 super.findCandidateAdvisors()方法最终调用的是BeanFactoryAdvisorRetrievalHelper.findAdvisorBeans()方法,我们首先看看该方法的实现:

 
  1. public List<Advisor> findAdvisorBeans() {

  2. String[] advisorNames = null;

  3. synchronized (this) {

  4. advisorNames = this.cachedAdvisorBeanNames;

  5. if (advisorNames == null) {

  6. // 获取当前BeanFactory中所有实现了Advisor接口的bean的名称

  7. advisorNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(

  8. this.beanFactory, Advisor.class, true, false);

  9. this.cachedAdvisorBeanNames = advisorNames;

  10. }

  11. }

  12. if (advisorNames.length == 0) {

  13. return new LinkedList<>();

  14. }

  15.  
  16. // 对获取到的实现Advisor接口的bean的名称进行遍历

  17. List<Advisor> advisors = new LinkedList<>();

  18. for (String name : advisorNames) {

  19. // isEligibleBean()是提供的一个hook方法,用于子类对Advisor进行过滤,这里默认返回值都是true

  20. if (isEligibleBean(name)) {

  21. // 如果当前bean还在创建过程中,则略过,其创建完成之后会为其判断是否需要织入切面逻辑

  22. if (this.beanFactory.isCurrentlyInCreation(name)) {

  23. if (logger.isDebugEnabled()) {

  24. logger.debug("Skipping currently created advisor '" + name + "'");

  25. }

  26. } else {

  27. try {

  28. // 将当前bean添加到结果中

  29. advisors.add(this.beanFactory.getBean(name, Advisor.class));

  30. } catch (BeanCreationException ex) {

  31. // 对获取过程中产生的异常进行封装

  32. Throwable rootCause = ex.getMostSpecificCause();

  33. if (rootCause instanceof BeanCurrentlyInCreationException) {

  34. BeanCreationException bce = (BeanCreationException) rootCause;

  35. String bceBeanName = bce.getBeanName();

  36. if (bceBeanName != null &&

  37. this.beanFactory.isCurrentlyInCreation(bceBeanName)) {

  38. if (logger.isDebugEnabled()) {

  39. logger.debug("Skipping advisor '" + name +

  40. "' with dependency on currently created bean: "

  41. + ex.getMessage());

  42. }

  43. continue;

  44. }

  45. }

  46. throw ex;

  47. }

  48. }

  49. }

  50. }

  51. return advisors;

  52. }

 

   然后其中的 buildAspectJAdvisors方法,会触发ReflectiveAspectJAdvisorFactory中的getAdvisors方法:

 
  1. @Override

  2. public List<Advisor> getAdvisors(MetadataAwareAspectInstanceFactory aspectInstanceFactory) {

  3. //从 aspectMetadata 中获取 Aspect()标注的类 class对象

  4. Class<?> aspectClass = aspectInstanceFactory.getAspectMetadata().getAspectClass();

  5. //获取Aspect()标注的类名

  6. String aspectName = aspectInstanceFactory.getAspectMetadata().getAspectName();

  7. validate(aspectClass);

  8.  
  9. // We need to wrap the MetadataAwareAspectInstanceFactory with a decorator

  10. // so that it will only instantiate once.

  11. MetadataAwareAspectInstanceFactory lazySingletonAspectInstanceFactory =

  12. new LazySingletonAspectInstanceFactoryDecorator(aspectInstanceFactory);

  13.  
  14. List<Advisor> advisors = new LinkedList<>();

  15. //遍历该类所有方法,根据方法判断是否能获取到对应 pointCut,如果有,则生成 advisor 对象

  16. for (Method method : getAdvisorMethods(aspectClass)) {

  17. //这里继续看下面的解析

  18. Advisor advisor = getAdvisor(method, lazySingletonAspectInstanceFactory, advisors.size(), aspectName);

  19. if (advisor != null) {

  20. advisors.add(advisor);

  21. }

  22. }

  23.  
  24. // If it's a per target aspect, emit the dummy instantiating aspect.

  25. if (!advisors.isEmpty() && lazySingletonAspectInstanceFactory.getAspectMetadata().isLazilyInstantiated()) {

  26. Advisor instantiationAdvisor = new SyntheticInstantiationAdvisor(lazySingletonAspectInstanceFactory);

  27. advisors.add(0, instantiationAdvisor);

  28. }

  29.  
  30. // Find introduction fields.

  31. //获取 @DeclareParents 注解修饰的属性(并不常用)

  32. for (Field field : aspectClass.getDeclaredFields()) {

  33. Advisor advisor = getDeclareParentsAdvisor(field);

  34. if (advisor != null) {

  35. advisors.add(advisor);

  36. }

  37. }

  38.  
  39. return advisors;

  40. }

 继续来看getAdvisor方法:

 
  1. @Override

  2. @Nullable

  3. public Advisor getAdvisor(Method candidateAdviceMethod, MetadataAwareAspectInstanceFactory aspectInstanceFactory,

  4. int declarationOrderInAspect, String aspectName) {

  5.  
  6. validate(aspectInstanceFactory.getAspectMetadata().getAspectClass());

  7. //根据候选方法名,来获取对应的 pointCut

  8. AspectJExpressionPointcut expressionPointcut = getPointcut(

  9. candidateAdviceMethod, aspectInstanceFactory.getAspectMetadata().getAspectClass());

  10. if (expressionPointcut == null) {

  11. return null;

  12. }

  13. //如果能获取到 pointCut,则将切点表达式 expressionPointcut、当前

  14. 对象ReflectiveAspectJAdvisorFactory、 方法名等包装成 advisor 对象

  15. return new InstantiationModelAwarePointcutAdvisorImpl(expressionPointcut, candidateAdviceMethod,

  16. this, aspectInstanceFactory, declarationOrderInAspect, aspectName);

  17. }

InstantiationModelAwarePointcutAdvisorImpl的构造方法会触发构造通知对象:

 
  1. public Advice getAdvice(Method candidateAdviceMethod, AspectJExpressionPointcut expressionPointcut,

  2. MetadataAwareAspectInstanceFactory aspectInstanceFactory, int declarationOrder, String aspectName) {

  3. //......

  4. //根据注解类型,匹配对应的通知类型

  5. switch (aspectJAnnotation.getAnnotationType()) {

  6. //前置通知

  7. case AtBefore:

  8. springAdvice = new AspectJMethodBeforeAdvice(

  9. candidateAdviceMethod, expressionPointcut, aspectInstanceFactory);

  10. break;

  11. //最终通知

  12. case AtAfter:

  13. springAdvice = new AspectJAfterAdvice(

  14. candidateAdviceMethod, expressionPointcut, aspectInstanceFactory);

  15. break;

  16. //后置通知

  17. case AtAfterReturning:

  18. springAdvice = new AspectJAfterReturningAdvice(

  19. candidateAdviceMethod, expressionPointcut, aspectInstanceFactory);

  20. AfterReturning afterReturningAnnotation = (AfterReturning) aspectJAnnotation.getAnnotation();

  21. if (StringUtils.hasText(afterReturningAnnotation.returning())) {

  22. springAdvice.setReturningName(afterReturningAnnotation.returning());

  23. }

  24. break;

  25. //异常通知

  26. case AtAfterThrowing:

  27. springAdvice = new AspectJAfterThrowingAdvice(

  28. candidateAdviceMethod, expressionPointcut, aspectInstanceFactory);

  29. AfterThrowing afterThrowingAnnotation = (AfterThrowing) aspectJAnnotation.getAnnotation();

  30. if (StringUtils.hasText(afterThrowingAnnotation.throwing())) {

  31. springAdvice.setThrowingName(afterThrowingAnnotation.throwing());

  32. }

  33. break;

  34. //环绕通知

  35. case AtAround:

  36. springAdvice = new AspectJAroundAdvice(

  37. candidateAdviceMethod, expressionPointcut, aspectInstanceFactory);

  38. break;

  39. //切面

  40. case AtPointcut:

  41. if (logger.isDebugEnabled()) {

  42. logger.debug("Processing pointcut '" + candidateAdviceMethod.getName() + "'");

  43. }

  44. return null;

  45. default:

  46. throw new UnsupportedOperationException(

  47. "Unsupported advice type on method: " + candidateAdviceMethod);

  48. }

  49.  
  50. //......

  51. }

 

可以看到,根据@Aspect类中方法的注解类型,生成对应的advice,并通过通知的构造方法,将通知增强方法,切面表达式传入到通知当中。

到这里InstantiationModelAwarePointcutAdvisorImpl对象构造完毕。

 

五 .介绍AbstractAutoProxyCreator中创建代理对象的过程:

原文:https://blog.csdn.net/uftjtt/article/details/80076733

Spring XML关于ProxyFactoryBean使用配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!-- 业务Bean -->
    <bean name="conferenceService" class="com.lanhuigu.spring.ConferenceServiceImpl"></bean>
 
    <!--配置Advice-->
    <bean name="logAdvice" class="com.lanhuigu.spring.aop.LoggerAdvice"></bean>
 
    <!--配置ProxyFactoryBean-->
    <bean name="aopMethod" class="org.springframework.aop.framework.ProxyFactoryBean">
        <!-- 指定通知器 -->
        <property name="interceptorNames">
            <list>
                <value>logAdvice</value>
            </list>
        </property>
        <!-- 需要增强的类 -->
        <property name="target" ref="conferenceService"/>
    </bean>
 
</beans>

AopProxy代理对象的生成过程:

 

 

 最后我们回到最初的AbstractAutoProxyCreator中的createProxy方法中

 
  1. protected Object createProxy(Class<?> beanClass, @Nullable String beanName,

  2. @Nullable Object[] specificInterceptors, TargetSource targetSource) {

  3.  
  4. if (this.beanFactory instanceof ConfigurableListableBeanFactory) {

  5. AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName, beanClass);

  6. }

  7.  
  8. ProxyFactory proxyFactory = new ProxyFactory();

  9. //获取当前类中的属性

  10. proxyFactory.copyFrom(this);

  11. //检查proxyTargeClass设置以及preserveTargetClass属性

  12. //决定对于给定的bean是否应该使用targetClass而不是他的接口代理

  13. if (!proxyFactory.isProxyTargetClass()) {

  14. if (shouldProxyTargetClass(beanClass, beanName)) {

  15. proxyFactory.setProxyTargetClass(true);

  16. }

  17. else {

  18. //用来添加代理接口

  19. evaluateProxyInterfaces(beanClass, proxyFactory);

  20. }

  21. }

  22.  
  23. Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);

  24. //加入增强器

  25. proxyFactory.addAdvisors(advisors);

  26. //设置要代理的类

  27. proxyFactory.setTargetSource(targetSource);

  28. //定制代理

  29. customizeProxyFactory(proxyFactory);

  30. //用来控制代理工厂被设置后是否还允许修改通知,缺省值为false

  31. proxyFactory.setFrozen(this.freezeProxy);

  32. if (advisorsPreFiltered()) {

  33. proxyFactory.setPreFiltered(true);

  34. }

  35.  
  36. return proxyFactory.getProxy(getProxyClassLoader());

  37. }

从上面代码我们看到对于代理类的创建及处理spring是委托给了ProxyFactory处理的,而在此函数中主要是对ProxyFactory的初始化操作,进而对创建代理做准备,这些初始化操作包括以下内容:
(1)获取当前类中的属性
(2)添加代理接口

下面是添加代理接口evaluateProxyInterfaces的函数:

 
  1. protected void evaluateProxyInterfaces(Class<?> beanClass, ProxyFactory proxyFactory) {

  2. Class<?>[] targetInterfaces = ClassUtils.getAllInterfacesForClass(beanClass, getProxyClassLoader());

  3. boolean hasReasonableProxyInterface = false;

  4. for (Class<?> ifc : targetInterfaces) {

  5. if (!isConfigurationCallbackInterface(ifc) && !isInternalLanguageInterface(ifc) &&

  6. ifc.getMethods().length > 0) {

  7. hasReasonableProxyInterface = true;

  8. break;

  9. }

  10. }

  11. if (hasReasonableProxyInterface) {

  12. // Must allow for introductions; can't just set interfaces to the target's interfaces only.

  13. for (Class<?> ifc : targetInterfaces) {

  14. proxyFactory.addInterface(ifc);

  15. }

  16. }

  17. else {

  18. proxyFactory.setProxyTargetClass(true);

  19. }

  20. }

(3)封装Advisor并加入到ProxyFactory中
(4)设置要代理的类
(5)在spring中还为子类提供了定制的函数customizeProxyFactory,子类可以在此函数中进行对ProxyFactory的进一步封装
(6)进行获取代理操作

在createProxy方法最后返回的getProxy方法中可以看到

 
  1. public Object getProxy(@Nullable ClassLoader classLoader) {

  2. return createAopProxy().getProxy(classLoader);

  3. }

在上面的getProxy方法中createAopProxy方法,其实现是在DefaultAopProxyFactory中,我们进入到方法内:

 
  1. @Override

  2. public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {

  3. if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {

  4. Class<?> targetClass = config.getTargetClass();

  5. if (targetClass == null) {

  6. throw new AopConfigException("TargetSource cannot determine target class: " +

  7. "Either an interface or a target is required for proxy creation.");

  8. }

  9. if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {

  10. return new JdkDynamicAopProxy(config);

  11. }

  12. return new ObjenesisCglibAopProxy(config);

  13. }

  14. else {

  15. return new JdkDynamicAopProxy(config);

  16. }

  17. }

 

六: Spring Boot 1.x 版本和 2.x版本 AOP 默认配置的变动

配置类AopAutoConfiguration:

1.5x版本:

    @Configuration
    @EnableAspectJAutoProxy(proxyTargetClass = true)
    @ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "true", matchIfMissing = false)
    public static class CglibAutoProxyConfiguration {

    }

2.x版本:

    @Configuration
    @EnableAspectJAutoProxy(proxyTargetClass = true)
    @ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "true", matchIfMissing = true)
    public static class CglibAutoProxyConfiguration {

    }

可以看到,在SpringBoot2.x中最主要的变化就是proxy-target-class默认为true,意味着类代理的时候全部走cglib代理方式,只有为接口代理时才走jdk代理(注意:这里为接口代理,不是指代理目标类是否实现了接口)。所以,在使用springboot2.x的版本中,除了代理目标类是接口外,其余的代理方式全部采用cglib类型。
总结

Springboot通过自动装配AopAutoConfiguration配置类,默认自动开启 AOP 功能。通过注册 AnnotationAwareAspectJAutoProxyCreator类,来扫描创建所有的Advisor,再通过 Advisor在 Spring IOC的扩展接口中来创建代理类。