死磕Spring AOP系列3:剖析Bean处理器之DefaultAdvisorAutoProxyCreator

简介:

这是<死磕Spring AOP系列>的第三篇。经过前面的讲解,已经掌握了以下知识点

  1. Spring AOP的底层支持,是基于ProxyFactory+ProxyConfig+Advisor生成的

  2. Spring容器的代理对象生成:在Bean生命周期过长中调用BeanPostProcessor,将对象进行包装,生成代理对象。

  3. Advisor的指定:不管编程式指定,还是自动匹配指定。虽然形式不同,但本质是相同的。

如果,还对上面的问题存疑,请回看以上内容。

本篇主要对剖析另外一个BeanPostProcessor,他就是DefaultAdvisorAutoProxyCreator,他是BeanNameAutoProxyCreator的升级版。形象点说:如果ProxyFactory是弓箭的话,代表原始,BeanNameAutoProxyCreator就是步枪,需要自己装配,DefaultAdvisorAutoProxyCreator就是自动步枪了,Spring可以完成自动匹配的部分工作了。

本章主要内容

  1. 使用DefaultAdvisorAutoProxyCreator,完成一个“AOP"例子,讲解下如何配置

  2. 对比BeanNameAutoProxyCreator,对DefaultAdvisorAutoProxyCreator进行剖析

  3. 分析DefaultAdvisorAutoProxyCreator的Advisor的匹配过程

  4. 体会自动化


1.使用DefaultAdvisorAutoProxyCreator,完成一个“AOP"例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
  *模拟业务接口
  */
public  interface  UserService {
     public  void  updateUser();
}
  
/**
  *模拟具体业务
  */
public  class  UserServiceImpl  implements  UserService{
  
     @Override
     public  void  updateUser() {
         System.out.println( "$$$$$$执行业务逻辑$$$$$" );
     }
}
  
/**
  * 模拟切面1
  */
public  class  SecurityInterceptor  implements  MethodInterceptor {
     @Override
     public  Object invoke(MethodInvocation methodInvocation)  throws  Throwable {
         System.out.println( "==========执行安全校验====================" );
         return  methodInvocation.proceed();
     }
}
  
/**
  * 模拟切面2
  */
public  class  LoggerBeforeAdvice  implements  MethodBeforeAdvice {
     @Override
     public  void  before(Method method, Object[] args, Object target)  throws  Throwable {
         System.out.println( "=======保存更新日志=========" );
     }
}

xml(proxy_test.xml)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<? xml  version = "1.0"  encoding = "UTF-8" ?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
 
< beans >
    < bean  class = "org.springaop.chap01.UserServiceImpl"  id = "userService" ></ bean >
    < bean  class = "org.springaop.chap01.LoggerBeforeAdvice"  id = "loggerBeforeAdvice" ></ bean >
    < bean  class = "org.springaop.chap01.SecurityInterceptor"  id = "securityInterceptor" ></ bean >
 
 
    <!-- 自动代理所有的advisor -->
    < bean  class = "org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" >
       < property  name = "usePrefix"  value = "true" ></ property >
       < property  name = "advisorBeanNamePrefix"  value = "advisor" ></ property >
    </ bean >
 
    < bean  id = "advisor1"  class = "org.springframework.aop.support.RegexpMethodPointcutAdvisor" >
       < property  name = "pattern" >
          < value >.*update.*</ value >   <!-- 业务实现方法名匹配 -->
       </ property >
       < property  name = "advice" >
          < ref  bean = "loggerBeforeAdvice" />
       </ property >
    </ bean >
 
    < bean  id = "advisor2"  class = "org.springframework.aop.support.RegexpMethodPointcutAdvisor" >
       < property  name = "pattern" >
          < value >.*update.*</ value >   <!-- 业务实现方法名匹配 -->
       </ property >
       < property  name = "advice" >
          < ref  bean = "securityInterceptor" />
       </ property >
    </ bean >
</ beans >

Main

1
2
3
4
5
6
7
8
9
public  class  ContextMain {
     public  static  void  main(String[] args) {
         ApplicationContext ctx =  new  ClassPathXmlApplicationContext( "org/springaop/chap03/proxy_test.xml" );
         UserService userService =(UserService) ctx.getBean( "userService" );
//        UserService userService2 =(UserService) ctx.getBean("userService2");
         userService.updateUser();
//        userService2.updateUser();
     }
}

执行结果

=======保存更新日志=========
==========执行安全校验====================
$$$$$$执行业务逻辑$$$$$


说明:usePrefix和advisorBeanNamePrefix配合使用,如果usePrefix设置为false,advisorBeanNamePrefix设置没有作用。通过上面的设置配置,advisor2和advisor都有效果。

2.剖析DefaultAdvisorAutoProxyCreator类

2.1 结构层次图

wKiom1dSRECQVFl4AACratmjUuY978.png


可知,DefaultAdvisorAutoProxyCreator,BeanNameAutoProxyCreator是AbstractAutoProxyCreator的子类。通过前面讲解,知道AbstractAutoProxyCreator有个抽象方法。

方法声明如下

1
2
3
4
//是否被代理?返回interceptors
//Return whether the given bean is to be proxied, what additional advices (e.g. AOP Alliance interceptors) and advisors to apply.
protected  abstract  Object[] getAdvicesAndAdvisorsForBean(
       Class<?> beanClass, String beanName, TargetSource customTargetSource)  throws  BeansException;

DefaultAdvisorAutoProxyCreator 和BeanNameAutoProxyCreator分别实现各自逻辑。BeanNameAutoProxyCreator的实现不再赘述,在死磕Spring AOP系列2已经讲过,代码很简单。

2.2 剖析getAdvicesAndAdvisorsForBean方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
public  abstract  class  AbstractAdvisorAutoProxyCreator  extends  AbstractAutoProxyCreator {
...
protected  Object[] getAdvicesAndAdvisorsForBean(Class beanClass, String beanName, TargetSource targetSource) {
    List advisors = findEligibleAdvisors(beanClass, beanName);
    if  (advisors.isEmpty()) {
       return  DO_NOT_PROXY;
    }
    return  advisors.toArray();
}
 
protected  List<Advisor> findEligibleAdvisors(Class beanClass, String beanName) {
    List<Advisor> candidateAdvisors = findCandidateAdvisors(); //获取所有的Advisors
    //获取可以应用于beanName的Advisor(逻辑尽在此)
    List<Advisor> eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);
    extendAdvisors(eligibleAdvisors);
    if  (!eligibleAdvisors.isEmpty()) {
       eligibleAdvisors = sortAdvisors(eligibleAdvisors);
    }
    return  eligibleAdvisors;
}
//Find all candidate Advisors to use in auto-proxying.
protected  List<Advisor> findCandidateAdvisors() {
    //委托给BeanFactoryAdvisorRetrievalHelper处理
    return  this .advisorRetrievalHelper.findAdvisorBeans();
}
 
}
public  class  BeanFactoryAdvisorRetrievalHelper {
     public  List<Advisor> findAdvisorBeans() {
 
...
           if  (advisorNames ==  null ) {
               //获取容器中声明的Advisor
              // Do not initialize FactoryBeans here: We need to leave all regular beans
              // uninitialized to let the auto-proxy creator apply to them!
              advisorNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
                    this .beanFactory, Advisor. class ,  true ,  false );
...
        }
        if  (advisorNames.length ==  0 ) {
           return  new  LinkedList<Advisor>();
        }
     
        List<Advisor> advisors =  new  LinkedList<Advisor>();
        for  (String name : advisorNames) {
            //判断返回
           if  (isEligibleBean(name) && ! this .beanFactory.isCurrentlyInCreation(name)) {
              try  {
                 advisors.add( this .beanFactory.getBean(name, Advisor. class ));
              }
              catch  (BeanCreationException ex) {
                 ...
                 throw  ex;
              }
           }
        }
        return  advisors;
     }
}

通过层层抽丝剥茧,定位到了AopUtils.findAdvisorsThatCanApply,负责具体的Advisor匹配工作。

3.剖析AopUtils.findAdvisorsThatCanApply方法,(匹配逻辑)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
protected  List<Advisor> findAdvisorsThatCanApply(
       List<Advisor> candidateAdvisors, Class beanClass, String beanName) {
 
    ProxyCreationContext.setCurrentProxiedBeanName(beanName);
    try  {
       return  AopUtils.findAdvisorsThatCanApply(candidateAdvisors, beanClass);
    }
    finally  {
       ProxyCreationContext.setCurrentProxiedBeanName( null );
    }
}
 
public  static  List<Advisor> findAdvisorsThatCanApply(List<Advisor> candidateAdvisors, Class<?> clazz) {
    if  (candidateAdvisors.isEmpty()) {
       return  candidateAdvisors;
    }
    List<Advisor> eligibleAdvisors =  new  LinkedList<Advisor>();
    for  (Advisor candidate : candidateAdvisors) { //遍历
       if  (candidate  instanceof  IntroductionAdvisor && canApply(candidate, clazz)) {
       //是否IntroductionAdvisor
          eligibleAdvisors.add(candidate);
       }
    }
    boolean  hasIntroductions = !eligibleAdvisors.isEmpty();
    for  (Advisor candidate : candidateAdvisors) {
       if  (candidate  instanceof  IntroductionAdvisor) {
          // already processed
          continue ;
       }
       if  (canApply(candidate, clazz, hasIntroductions)) { //执行
          eligibleAdvisors.add(candidate);
       }
    }
    return  eligibleAdvisors;
}
 
public  static  boolean  canApply(Advisor advisor, Class<?> targetClass,  boolean  hasIntroductions) {
    if  (advisor  instanceof  IntroductionAdvisor) {
       return  ((IntroductionAdvisor) advisor).getClassFilter().matches(targetClass);
    }
    else  if  (advisor  instanceof  PointcutAdvisor) {
       PointcutAdvisor pca = (PointcutAdvisor) advisor;
       return  canApply(pca.getPointcut(), targetClass, hasIntroductions);
    }
    else  {
       // It doesn't have a pointcut so we assume it applies.
       return  true ;
    }
}
 
 
public  static  boolean  canApply(Pointcut pc, Class<?> targetClass,  boolean  hasIntroductions) {
    Assert.notNull(pc,  "Pointcut must not be null" );
    if  (!pc.getClassFilter().matches(targetClass)) {
       return  false ;
    }
 
    MethodMatcher methodMatcher = pc.getMethodMatcher();
    IntroductionAwareMethodMatcher introductionAwareMethodMatcher =  null ;
    if  (methodMatcher  instanceof  IntroductionAwareMethodMatcher) {
       introductionAwareMethodMatcher = (IntroductionAwareMethodMatcher) methodMatcher;
    }
 
    Set<Class> classes =  new  HashSet<Class>(ClassUtils.getAllInterfacesForClassAsSet(targetClass));
    classes.add(targetClass);
    for  (Class<?> clazz : classes) {
       Method[] methods = clazz.getMethods();
       for  (Method method : methods) {
          if  ((introductionAwareMethodMatcher !=  null  &&
                introductionAwareMethodMatcher.matches(method, targetClass, hasIntroductions)) ||
                methodMatcher.matches(method, targetClass)) { //methodMatcher具体完成匹配
             return  true ;
          }
       }
    }
 
    return  false ;
}


wKioL1dSUh-BaDsIAABPQ2m8W1U171.png

通过图得知Advisor,持有Advice的聚合信息和PointCut对象,而PointCut接口持有MethodMatcher。

最后MethodMatcher完成方法匹配工作。以当前例子为例,AbstractRegexpMethodPointcut同时也是MethodMatcher.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
public  abstract  class  AbstractRegexpMethodPointcut  extends  StaticMethodMatcherPointcut
       implements  Serializable {
public  boolean  matches(Method method, Class targetClass) {
    return  ((targetClass !=  null  && matchesPattern(targetClass.getName() +  "."  + method.getName())) ||
          matchesPattern(method.getDeclaringClass().getName() +  "."  + method.getName()));
}
}
 
protected  boolean  matchesPattern(String signatureString) {
    for  ( int  i =  0 ; i <  this .patterns.length; i++) {
       boolean  matched = matches(signatureString, i);
       if  (matched) {
          for  ( int  j =  0 ; j <  this .excludedPatterns.length; j++) {
             boolean  excluded = matchesExclusion(signatureString, j);
             if  (excluded) {
                return  false ;
             }
          }
          return  true ;
       }
    }
    return  false ;
}
 
public  class  JdkRegexpMethodPointcut  extends  AbstractRegexpMethodPointcut {
/**
  * Returns {@code true} if the {@link Pattern} at index {@code patternIndex}
  * matches the supplied candidate {@code String}.
  */
@Override
protected  boolean  matches(String pattern,  int  patternIndex) {
    Matcher matcher =  this .compiledPatterns[patternIndex].matcher(pattern);
    return  matcher.matches();
}
 
/**
  * Returns {@code true} if the exclusion {@link Pattern} at index {@code patternIndex}
  * matches the supplied candidate {@code String}.
  */
@Override
protected  boolean  matchesExclusion(String candidate,  int  patternIndex) {
    Matcher matcher =  this .compiledExclusionPatterns[patternIndex].matcher(candidate);
    return  matcher.matches();
}
 
 
/**
  * Compiles the supplied {@code String[]} into an array of
  * {@link Pattern} objects and returns that array.
  */
private  Pattern[] compilePatterns(String[] source)  throws  PatternSyntaxException {
    Pattern[] destination =  new  Pattern[source.length];
    for  ( int  i =  0 ; i < source.length; i++) {
       destination[i] = Pattern.compile(source[i]);
    }
    return  destination;
}
}

4.自动化

比起BeanNameAutoProxyCreator,DefaultAdvisorAutoProxyCreator有一个非常优越的地方。那就是advisor已有了自动匹配方法的能力。具体实现逻辑,通过上面的分析就是正则表达式的使用。其实很简单,确定一个方法是否被应用于advice,其实就是讲方法的签名字符串与定义PointCut的pattern进行匹配。今天提到的JdkRegexpMethodPointcut,只是实现之一。另外一个更强大的PointCut是什么?下次再说。



本文转自 randy_shandong 51CTO博客,原文链接:http://blog.51cto.com/dba10g/1786057,如需转载请自行联系原作者

相关文章
|
XML 安全 Java
使用 Spring 的 @Aspect 和 @Pointcut 注解简化面向方面的编程 (AOP)
面向方面编程(AOP)通过分离横切关注点,如日志、安全和事务,提升代码模块化与可维护性。Spring 提供了对 AOP 的强大支持,核心注解 `@Aspect` 和 `@Pointcut` 使得定义切面与切入点变得简洁直观。`@Aspect` 标记切面类,集中处理通用逻辑;`@Pointcut` 则通过表达式定义通知的应用位置,提高代码可读性与复用性。二者结合,使开发者能清晰划分业务逻辑与辅助功能,简化维护并提升系统灵活性。Spring AOP 借助代理机制实现运行时织入,与 Spring 容器无缝集成,支持依赖注入与声明式配置,是构建清晰、高内聚应用的理想选择。
1082 0
|
监控 安全 Java
Spring AOP实现原理
本内容主要介绍了Spring AOP的核心概念、实现机制及代理生成流程。涵盖切面(Aspect)、连接点(Join Point)、通知(Advice)、切点(Pointcut)等关键概念,解析了JDK动态代理与CGLIB代理的原理及对比,并深入探讨了通知执行链路和责任链模式的应用。同时,详细分析了AspectJ注解驱动的AOP解析过程,包括切面识别、切点表达式匹配及通知适配为Advice的机制,帮助理解Spring AOP的工作原理与实现细节。
1917 13
|
XML Java 测试技术
Spring IOC—基于注解配置和管理Bean 万字详解(通俗易懂)
Spring 第三节 IOC——基于注解配置和管理Bean 万字详解!
1207 26
|
XML Java 开发者
Spring Boot中的AOP实现
Spring AOP(面向切面编程)允许开发者在不修改原有业务逻辑的情况下增强功能,基于代理模式拦截和增强方法调用。Spring Boot通过集成Spring AOP和AspectJ简化了AOP的使用,只需添加依赖并定义切面类。关键概念包括切面、通知和切点。切面类使用`@Aspect`和`@Component`注解标注,通知定义切面行为,切点定义应用位置。Spring Boot自动检测并创建代理对象,支持JDK动态代理和CGLIB代理。通过源码分析可深入了解其实现细节,优化应用功能。
907 6
|
XML Java 数据格式
《深入理解Spring》:AOP面向切面编程深度解析
Spring AOP通过代理模式实现面向切面编程,将日志、事务等横切关注点与业务逻辑分离。支持注解、XML和编程式配置,提供五种通知类型及丰富切点表达式,助力构建高内聚、低耦合的可维护系统。
|
人工智能 监控 安全
Spring AOP切面编程颠覆传统!3大核心注解+5种通知类型,让业务代码纯净如初
本文介绍了AOP(面向切面编程)的基本概念、优势及其在Spring Boot中的使用。AOP作为OOP的补充,通过将横切关注点(如日志、安全、事务等)与业务逻辑分离,实现代码解耦,提升模块化程度、可维护性和灵活性。文章详细讲解了Spring AOP的核心概念,包括切面、切点、通知等,并提供了在Spring Boot中实现AOP的具体步骤和代码示例。此外,还列举了AOP在日志记录、性能监控、事务管理和安全控制等场景中的实际应用。通过本文,开发者可以快速掌握AOP编程思想及其实践技巧。
|
人工智能 监控 安全
如何快速上手【Spring AOP】?核心应用实战(上篇)
哈喽大家好吖~欢迎来到Spring AOP系列教程的上篇 - 应用篇。在本篇,我们将专注于Spring AOP的实际应用,通过具体的代码示例和场景分析,帮助大家掌握AOP的使用方法和技巧。而在后续的下篇中,我们将深入探讨Spring AOP的实现原理和底层机制。 AOP(Aspect-Oriented Programming,面向切面编程)是Spring框架中的核心特性之一,它能够帮助我们解决横切关注点(如日志记录、性能统计、安全控制、事务管理等)的问题,提高代码的模块化程度和复用性。
1066 1
|
设计模式 Java 开发者
如何快速上手【Spring AOP】?从动态代理到源码剖析(下篇)
Spring AOP的实现本质上依赖于代理模式这一经典设计模式。代理模式通过引入代理对象作为目标对象的中间层,实现了对目标对象访问的控制与增强,其核心价值在于解耦核心业务逻辑与横切关注点。在框架设计中,这种模式广泛用于实现功能扩展(如远程调用、延迟加载)、行为拦截(如权限校验、异常处理)等场景,为系统提供了更高的灵活性和可维护性。
1706 0
|
XML Java 测试技术
Spring AOP—通知类型 和 切入点表达式 万字详解(通俗易懂)
Spring 第五节 AOP——切入点表达式 万字详解!
1428 25
|
XML 安全 Java
Spring AOP—深入动态代理 万字详解(通俗易懂)
Spring 第四节 AOP——动态代理 万字详解!
745 24