资讯专栏INFORMATION COLUMN

Spring AOP 源码初窥(三)扫描Advice与Bean匹配

oysun / 1137人阅读

摘要:版本如何扫描接上一回,讲到了方法,该方法的目的是获取并生成。其中英文为源码注释。那么,以上便是通过扫描配置并生成的过程了。一些总结读到这儿,如何扫描配置,生成类,并匹配对应的整个流程已经很清楚了。

版本

spring 5.0.8.BUILD-SNAPSHOT

aspectjweaver 1.8.13

如何扫描Advice

接上一回,讲到了getAdvicesAndAdvisorsForBean方法,该方法的目的是获取并生成Advisor Bean。其中包含了扫描通过@Aspect注解配置且与Bean方法的匹配的Advice,也是本章主要讲的内容

getAdvicesAndAdvisorsForBean

</>复制代码

  1. /org/springframework/aop/framework/autoproxy/AbstractAdvisorAutoProxyCreator.java
  2. @Override
  3. @Nullable
  4. protected Object[] getAdvicesAndAdvisorsForBean(
  5. Class beanClass, String beanName, @Nullable TargetSource targetSource) {
  6. List advisors = findEligibleAdvisors(beanClass, beanName);
  7. if (advisors.isEmpty()) {
  8. return DO_NOT_PROXY;
  9. }
  10. return advisors.toArray();
  11. }
  12. /**
  13. * Find all eligible Advisors for auto-proxying this class.
  14. * @param beanClass the clazz to find advisors for
  15. * @param beanName the name of the currently proxied bean
  16. * @return the empty List, not {@code null},
  17. * if there are no pointcuts or interceptors
  18. * @see #findCandidateAdvisors
  19. * @see #sortAdvisors
  20. * @see #extendAdvisors
  21. */
  22. protected List findEligibleAdvisors(Class beanClass, String beanName) {
  23. List candidateAdvisors = findCandidateAdvisors();
  24. List eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);
  25. extendAdvisors(eligibleAdvisors);
  26. if (!eligibleAdvisors.isEmpty()) {
  27. eligibleAdvisors = sortAdvisors(eligibleAdvisors);
  28. }
  29. return eligibleAdvisors;
  30. }
  31. ....

关注findEligibleAdvisors方法可以清楚地知道这里主要分四步:

findCandidateAdvisors (获取候选Advisor)

findAdvisorsThatCanApply (获取适用于bean的Advisor: 例如Pointcut匹配)

extendAdvisors (特殊处理,这里不赘述)

sortAdvisors (排序,不赘述)

</>复制代码

  1. 什么是Advisor? 首先,Advice是增强方法,即@Around, @Before等注解修饰的方法。而Advisor则是在Advice之上再包了一层。例如PointcutAdvisor则包有Advice和Pointcut

下面接着看findCandidateAdvisors和findAdvisorsThatCanApply

findCandidateAdvisors

</>复制代码

  1. /org/springframework/aop/framework/autoproxy/AbstractAdvisorAutoProxyCreator.java
  2. ....
  3. /**
  4. * Find all candidate Advisors to use in auto-proxying.
  5. * @return the List of candidate Advisors
  6. */
  7. protected List findCandidateAdvisors() {
  8. Assert.state(this.advisorRetrievalHelper != null, "No BeanFactoryAdvisorRetrievalHelper available");
  9. return this.advisorRetrievalHelper.findAdvisorBeans();
  10. }
  11. ....
  12. /org/springframework/aop/aspectj/annotation/AnnotationAwareAspectJAutoProxyCreator.java
  13. ....
  14. @Override
  15. protected List findCandidateAdvisors() {
  16. // Add all the Spring advisors found according to superclass rules.
  17. List advisors = super.findCandidateAdvisors();
  18. // Build Advisors for all AspectJ aspects in the bean factory.
  19. if (this.aspectJAdvisorsBuilder != null) {
  20. advisors.addAll(this.aspectJAdvisorsBuilder.buildAspectJAdvisors());
  21. }
  22. return advisors;
  23. }
  24. ....

这里findCandidateAdvisors在AbstractAdvisorAutoProxyCreator中有实现,同时被AnnotationAwareAspectJAutoProxyCreator重写了。不过可以看到重写的方法中先调用了super.findCandidateAdvisor,因此两个方法的代码都被执行了。

this.advisorRetrievalHelper.findAdvisorBeans (该方法主要从BeanFactory中获取Advisor Bean)

this.aspectJAdvisorsBuilder.buildAspectJAdvisors (从所有Bean中获取@Aspect配置的Bean并创建Advisor,也是我们关注的内容,下面细讲)

buildAspectJAdvisors

</>复制代码

  1. /org/springframework/aop/aspectj/annotation/BeanFactoryAspectJAdvisorsBuilder.java
  2. ....
  3. /**
  4. * Look for AspectJ-annotated aspect beans in the current bean factory,
  5. * and return to a list of Spring AOP Advisors representing them.
  6. *

    Creates a Spring Advisor for each AspectJ advice method.

  7. * @return the list of {@link org.springframework.aop.Advisor} beans
  8. * @see #isEligibleBean
  9. */
  10. public List buildAspectJAdvisors() {
  11. // aspectBeanNames,缓存
  12. // tips: aspectBeanNames由volatile修饰
  13. // volatile: 保证变量可见性,指令不可重排
  14. List aspectNames = this.aspectBeanNames;
  15. // 如缓存存在,则跳过初始化步骤
  16. if (aspectNames == null) {
  17. // synchronized, 同步锁
  18. // 锁住当前实例,里面的内容同一时间只会被一个线程执行
  19. synchronized (this) {
  20. // 拿到锁后再次获取缓存,避免重复初始化
  21. aspectNames = this.aspectBeanNames;
  22. if (aspectNames == null) {
  23. List advisors = new ArrayList<>();
  24. aspectNames = new ArrayList<>();
  25. // 获取原始类为Object的bean,即所有bean
  26. String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
  27. this.beanFactory, Object.class, true, false);
  28. for (String beanName : beanNames) {
  29. // 是否是合适的bean
  30. if (!isEligibleBean(beanName)) {
  31. continue;
  32. }
  33. // We must be careful not to instantiate beans eagerly as in this case they
  34. // would be cached by the Spring container but would not have been weaved.
  35. Class beanType = this.beanFactory.getType(beanName);
  36. if (beanType == null) {
  37. continue;
  38. }
  39. // isAspect 是否为@Aspect注解修饰的Bean
  40. // 是不是很亲切方法,终于读到它了。这是我们在第二章一开始就提到的方法。
  41. if (this.advisorFactory.isAspect(beanType)) {
  42. aspectNames.add(beanName);
  43. // 由beanType,beanName组合Metadata,包含了创建Advisor需要的内容
  44. AspectMetadata amd = new AspectMetadata(beanType, beanName);
  45. // PerClauseKind.SINGLETON 单例模式
  46. // 由@Aspect中的value参数配置,这个参数Bean的scope 有点类似,用来配置生命 周期,默认都为单例。可配为"每..."的模式
  47. if (amd.getAjType().getPerClause().getKind() == PerClauseKind.SINGLETON) {
  48. // 生成实例工厂类
  49. MetadataAwareAspectInstanceFactory factory =
  50. new BeanFactoryAspectInstanceFactory(this.beanFactory, beanName);
  51. // 生成Advisors实例
  52. List classAdvisors = this.advisorFactory.getAdvisors(factory);
  53. // 如果Aspect Bean是单例,则缓存到advisorsCache
  54. if (this.beanFactory.isSingleton(beanName)) {
  55. this.advisorsCache.put(beanName, classAdvisors);
  56. }
  57. // 如果不是,则将工厂缓存到aspectFactoryCache
  58. else {
  59. this.aspectFactoryCache.put(beanName, factory);
  60. }
  61. advisors.addAll(classAdvisors);
  62. }
  63. else {
  64. // Per target or per this.
  65. // bean为单例,@Aspect也要配置为单例
  66. if (this.beanFactory.isSingleton(beanName)) {
  67. throw new IllegalArgumentException("Bean with name "" + beanName +
  68. "" is a singleton, but aspect instantiation model is not singleton");
  69. }
  70. // 跟前一个分支一样,生成Advisors实例,然后将工厂缓存到aspectFactoryCache
  71. MetadataAwareAspectInstanceFactory factory =
  72. new PrototypeAspectInstanceFactory(this.beanFactory, beanName);
  73. this.aspectFactoryCache.put(beanName, factory);
  74. advisors.addAll(this.advisorFactory.getAdvisors(factory));
  75. }
  76. }
  77. }
  78. this.aspectBeanNames = aspectNames;
  79. return advisors;
  80. }
  81. }
  82. }
  83. if (aspectNames.isEmpty()) {
  84. return Collections.emptyList();
  85. }
  86. List advisors = new ArrayList<>();
  87. for (String aspectName : aspectNames) {
  88. // 通过aspectName(beanName)获取advisors缓存
  89. List cachedAdvisors = this.advisorsCache.get(aspectName);
  90. // 如已存在,则加载advisorsCache
  91. if (cachedAdvisors != null) {
  92. advisors.addAll(cachedAdvisors);
  93. }
  94. // 如不存在,则加载factoryCache,再从工厂生成advisors,与上面初始时候的两个分支对应
  95. // ps:这里并没有做factory的空判断...
  96. else {
  97. MetadataAwareAspectInstanceFactory factory = this.aspectFactoryCache.get(aspectName);
  98. advisors.addAll(this.advisorFactory.getAdvisors(factory));
  99. }
  100. }
  101. return advisors;
  102. }
  103. ....

由于这段代码比较长,我将过程注释在代码中。其中英文为源码注释。

那么,以上便是通过beanName扫描@Aspect配置并生成Advisor的过程了。其中this.advisorFactory.getAdvisors(factory)是生成Advisor类的具体内容。深挖的话还能再写一篇文章,这里就不细说了。有兴趣的可以自行阅读。

findAdvisorsThatCanApply

现在我们获得了所有的候选Advisor,那么找出和当前Bean匹配的Advisor呢?

</>复制代码

  1. /org/springframework/aop/framework/autoproxy/AbstractAdvisorAutoProxyCreator.java
  2. ....
  3. /**
  4. * Search the given candidate Advisors to find all Advisors that
  5. * can apply to the specified bean.
  6. * @param candidateAdvisors the candidate Advisors
  7. * @param beanClass the target"s bean class
  8. * @param beanName the target"s bean name
  9. * @return the List of applicable Advisors
  10. * @see ProxyCreationContext#getCurrentProxiedBeanName()
  11. */
  12. protected List findAdvisorsThatCanApply(
  13. List candidateAdvisors, Class beanClass, String beanName) {
  14. ProxyCreationContext.setCurrentProxiedBeanName(beanName);
  15. try {
  16. return AopUtils.findAdvisorsThatCanApply(candidateAdvisors, beanClass);
  17. }
  18. finally {
  19. ProxyCreationContext.setCurrentProxiedBeanName(null);
  20. }
  21. }
  22. ....

一步一步往下探

</>复制代码

  1. /org/springframework/aop/support/AopUtils.java
  2. ....
  3. /**
  4. * Determine the sublist of the {@code candidateAdvisors} list
  5. * that is applicable to the given class.
  6. * @param candidateAdvisors the Advisors to evaluate
  7. * @param clazz the target class
  8. * @return sublist of Advisors that can apply to an object of the given class
  9. * (may be the incoming List as-is)
  10. */
  11. public static List findAdvisorsThatCanApply(List candidateAdvisors, Class clazz) {
  12. if (candidateAdvisors.isEmpty()) {
  13. return candidateAdvisors;
  14. }
  15. List eligibleAdvisors = new ArrayList<>();
  16. for (Advisor candidate : candidateAdvisors) {
  17. if (candidate instanceof IntroductionAdvisor && canApply(candidate, clazz)) {
  18. eligibleAdvisors.add(candidate);
  19. }
  20. }
  21. boolean hasIntroductions = !eligibleAdvisors.isEmpty();
  22. for (Advisor candidate : candidateAdvisors) {
  23. if (candidate instanceof IntroductionAdvisor) {
  24. // already processed
  25. continue;
  26. }
  27. if (canApply(candidate, clazz, hasIntroductions)) {
  28. eligibleAdvisors.add(candidate);
  29. }
  30. }
  31. return eligibleAdvisors;
  32. }
  33. ....
  34. /**
  35. * Can the given advisor apply at all on the given class?
  36. * This is an important test as it can be used to optimize
  37. * out a advisor for a class.
  38. * @param advisor the advisor to check
  39. * @param targetClass class we"re testing
  40. * @return whether the pointcut can apply on any method
  41. */
  42. public static boolean canApply(Advisor advisor, Class targetClass) {
  43. return canApply(advisor, targetClass, false);
  44. }
  45. /**
  46. * Can the given advisor apply at all on the given class?
  47. *

    This is an important test as it can be used to optimize out a advisor for a class.

  48. * This version also takes into account introductions (for IntroductionAwareMethodMatchers).
  49. * @param advisor the advisor to check
  50. * @param targetClass class we"re testing
  51. * @param hasIntroductions whether or not the advisor chain for this bean includes
  52. * any introductions
  53. * @return whether the pointcut can apply on any method
  54. */
  55. public static boolean canApply(Advisor advisor, Class targetClass, boolean hasIntroductions) {
  56. if (advisor instanceof IntroductionAdvisor) {
  57. return ((IntroductionAdvisor) advisor).getClassFilter().matches(targetClass);
  58. }
  59. else if (advisor instanceof PointcutAdvisor) {
  60. PointcutAdvisor pca = (PointcutAdvisor) advisor;
  61. return canApply(pca.getPointcut(), targetClass, hasIntroductions);
  62. }
  63. else {
  64. // It doesn"t have a pointcut so we assume it applies.
  65. return true;
  66. }
  67. }
  68. ....

最后定位到canApply(Pointcut pc, Class targetClass, boolean hasIntroductions)方法

</>复制代码

  1. /org/springframework/aop/support/AopUtils.java
  2. /**
  3. * Can the given pointcut apply at all on the given class?
  4. *

    This is an important test as it can be used to optimize

  5. * out a pointcut for a class.
  6. * @param pc the static or dynamic pointcut to check
  7. * @param targetClass the class to test
  8. * @param hasIntroductions whether or not the advisor chain
  9. * for this bean includes any introductions
  10. * @return whether the pointcut can apply on any method
  11. */
  12. public static boolean canApply(Pointcut pc, Class targetClass, boolean hasIntroductions) {
  13. Assert.notNull(pc, "Pointcut must not be null");
  14. if (!pc.getClassFilter().matches(targetClass)) {
  15. return false;
  16. }
  17. MethodMatcher methodMatcher = pc.getMethodMatcher();
  18. if (methodMatcher == MethodMatcher.TRUE) {
  19. // No need to iterate the methods if we"re matching any method anyway...
  20. return true;
  21. }
  22. IntroductionAwareMethodMatcher introductionAwareMethodMatcher = null;
  23. if (methodMatcher instanceof IntroductionAwareMethodMatcher) {
  24. introductionAwareMethodMatcher = (IntroductionAwareMethodMatcher) methodMatcher;
  25. }
  26. Set> classes = new LinkedHashSet<>();
  27. if (!Proxy.isProxyClass(targetClass)) {
  28. classes.add(ClassUtils.getUserClass(targetClass));
  29. }
  30. classes.addAll(ClassUtils.getAllInterfacesForClassAsSet(targetClass));
  31. for (Class clazz : classes) {
  32. Method[] methods = ReflectionUtils.getAllDeclaredMethods(clazz);
  33. for (Method method : methods) {
  34. if (introductionAwareMethodMatcher != null ?
  35. introductionAwareMethodMatcher.matches(method, targetClass, hasIntroductions) :
  36. methodMatcher.matches(method, targetClass)) {
  37. return true;
  38. }
  39. }
  40. }
  41. return false;
  42. }

可以看出判断是否是该bean合适的advisor,是通过advisor.getPointcut().getClassFilter().matches(targetClass)方法来判断的。匹配完class以后下面还有MethodMatcher来匹配method。回想我们在配置pointcut的时候不仅仅有class的规则,也有method的规则。

当然,再深入matches方法进去的话就是pointcut的匹配语法实现了。有兴趣的可以自行阅读。

一些总结

读到这儿,Spring AOP如何扫描@Aspect配置,生成Advisor类,并匹配对应的Bean整个流程已经很清楚了。这里再总结一下:

获取已在BeanFactory的Advisor Bean

获取所有Object Bean,过滤出@Aspect注解修饰的Bean,并生成Advisor

遍历上述获取的所有Advisor,由Advisor的Pointcut ClassFilter匹配合适的Bean

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/76783.html

相关文章

  • Spring AOP 源码初窥(二) 从注解开始

    摘要:版本从注解开始由于在本人实际应用中使用的是注解配置,也更倾向于了解的整个实现,而不仅仅是关键实现。于是本篇源码解析,将会从注解开始。那么,便从的源码引用开始吧。的引用先从源码中找有引用到,用来判断是否有该注解的代码。 版本 spring 5.0.8.BUILD-SNAPSHOT aspectjweaver 1.8.13 从注解开始 由于在本人实际应用中使用的是注解配置AOP,也更倾...

    Amio 评论0 收藏0
  • 源码入手,一文带你读懂Spring AOP面向切面编程

    摘要:,,面向切面编程。,切点,切面匹配连接点的点,一般与切点表达式相关,就是切面如何切点。例子中,注解就是切点表达式,匹配对应的连接点,通知,指在切面的某个特定的连接点上执行的动作。,织入,将作用在的过程。因为源码都是英文写的。 之前《零基础带你看Spring源码——IOC控制反转》详细讲了Spring容器的初始化和加载的原理,后面《你真的完全了解Java动态代理吗?看这篇就够了》介绍了下...

    wawor4827 评论0 收藏0
  • Spring AOP 源码初窥(一) 概念

    摘要:而面向切面编程理所当然关注于切面,那么什么是切面可以理解为程序执行时的某个节点,或更具体一点,在某个方法执行之前,执行之后,返回之后等其它节点。术语一个切面,可以理解为一个切面模块,将相关的增强内容写进同一个切面。例如一个负责日志的切面。 AOP是什么 AOP全称 Aspect-Oriented Programming 即面向切面编程。怎么样,是不是感觉很熟悉?对,类似的还有面向过程编...

    CarterLi 评论0 收藏0
  • 慕课网_《Spring入门篇》学习总结

    摘要:入门篇学习总结时间年月日星期三说明本文部分内容均来自慕课网。主要的功能是日志记录,性能统计,安全控制,事务处理,异常处理等等。 《Spring入门篇》学习总结 时间:2017年1月18日星期三说明:本文部分内容均来自慕课网。@慕课网:http://www.imooc.com教学示例源码:https://github.com/zccodere/s...个人学习源码:https://git...

    Ververica 评论0 收藏0
  • 重拾-Spring AOP-自动代理

    摘要:是通过判断当前是否匹配,只有匹配的才会创建代理。实现分析类结构从上图类结构,我们知道其实现与类似都是通过实现接口在完成实例化后进行自动代理处理。 概述 在上一篇 重拾-Spring AOP 中我们会发现 Spring AOP 是通过类 ProxyFactoryBean 创建代理对象,其有个缺陷就是只能代理一个目标对象 bean, 当代理目标类过多时,配置文件臃肿不方便管理维护,因此 S...

    Mr_houzi 评论0 收藏0

发表评论

0条评论

oysun

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<