Spring AOP overview

Full moon acridine 2021-04-16 14:38:20
spring aop overview


This series of articles is my study Spring In the process of summing up , Which involves the relevant source code , May not be very friendly to readers , Please combine with my source code comments Spring Source code analysis GitHub Address To read .

Spring edition :5.1.14.RELEASE

At the beginning of reading Spring AOP Before source code , Need to be right Spring IoC Have some understanding , Check out my 《 screwing Spring And IoC piece - Article reading guidance 》 This series of articles

understand AOP Related terms , You can check 《Spring AOP Frequently asked questions ) 》 This article

For other articles in the series, check out :《 screwing Spring And AOP piece - Article reading guidance 》

Through the previous article 《 First time to know JDK、CGLIB Two kinds of dynamic agents 》 In this article, we are interested in Spring AOP At the bottom JDK Dynamic proxy sum CGLIB Dynamic agents have a certain understanding of , You also know how to simply create proxy objects using two dynamic proxies . I believe the last article can help you understand Spring AOP Have a preliminary understanding , So next we're going to go into Spring AOP Source code learning stage .

At the beginning Spring AOP Before learning the source code , This article will Spring AOP Most of the major ones involved are API To introduce , Let's be right Spring AOP Have a comprehensive understanding of , This is learning Spring AOP Having a clear idea in the process of source code will make it easier to understand , And then in the following article from Spring AOP Of Automatic agent Start learning in depth , Let's get straight to the point .

Spring AOP API The overview

As shown in the figure below :

The picture above lists Spring AOP Most of them API, Next, let's briefly introduce :

  • Joinpoint: Connection point , That's what we need to do

  • Pointcut: Tangent point , Provide ClassFilter Class filters and MethodMatcher The method matcher supports class and method filtering .

  • Advice: Notifier , It's usually MethodInterceptor method interceptors , If not, it will pass AdvisorAdapter The adapter converts to the corresponding MethodInterceptor method interceptors .

  • Advisor:Advice Container interface , And Advice It's a one-to-one relationship ; Its sub interface PointcutAdvisor Equivalent to a kind of Pointcut and Advice The container of , take Pointcut Filter Joinpoint Ability and Advice Integration , That's how it connects the two .

  • Advisor Adapter AdvisorAdapter yes Advisor Adapter for , When you filter out all the things that can be applied to the method Advisor after , You need to get the corresponding Advice;

    • If not MethodInterceptor type , You have to go through AdvisorAdapter The adapter converts to the corresponding MethodInterceptor method interceptors .
  • AOP Proxy object :AOP Proxy object , from JDK Dynamic agents or CGLIB Proxy object created by dynamic proxy ;

    • Choose which dynamic agent is through AopProxyFactory The agent factory is determined by the target class .
  • AOP Agent configuration AdvisedSupport The configuration manager stores the configuration information of the corresponding proxy object , For example, if the conditions are met Advisor object 、TargetSource Target class source ;

    • In the process of creating a proxy object ,AdvisedSupport Plays a very important role .
  • AOP Proxy object creation :AOP The creation of proxy objects is divided into Manual mode and Automatic mode ; Either model is similar to AdvisedSupport Configuration manager ;

    • Manual mode It is through Spring AOP Provided API Create ;
    • Automatic mode And Spring IoC Integration , stay Bean If proxy is needed during the loading process of , Then create the corresponding proxy object ;
  • AdvisorChainFactoryAdvisor Link factory

    • AdvisedSupport The configuration manager stores all of the proxy objects Advisor object , When intercepting a method , Need to pass through AdvisorChainFactory The results show that the method can be applied to Advisor People ;
    • In addition, we need the help of AdvisorAdapter The adapter gets Advisor Corresponding MethodInterceptor method interceptors , Will these MethodInterceptor Orderly form a link and return .
  • IntroductionInfo introducing Interface , Support for proxy object implementation. The target class doesn't really implement additional interfaces ;

    • stay Advisor Sub interface of IntroductionAdvisor I'm going to inherit this IntroductionInfo Interface , adopt @DeclareParents The fields defined by the annotation are resolved to IntroductionAdvisor object .
  • AOP Proxy target object source Target class source , Associate with a proxy object , Used to get the target object of the proxy ;

    • In the proxy object, the final method execution needs to go through TargetSource Get the corresponding target object , Then execute the target method .

Joinpoint

Class diagram

  • ConstructorInvocation, It's a caller based on the constructor , stay Spring AOP Only method level proxies are supported in , So this interface is not used

  • ReflectiveMethodInvocation,Joinpoint The underlying implementation class of , A reflection based method caller , This paper does not analyze , In the following article to explain

  • CglibMethodInvocation, Similar to the above implementation class , I added a new one CGLIB Medium MethodProxy Method proxy object , This paper does not analyze , In the following article to explain

org.aopalliance.intercept.Joinpoint, Connection point , That's what we need to do , By AOP An interface to the Alliance , as follows :

public interface Joinpoint {
/**
* Execute the next interceptor in the method caller , After all interceptors are executed, the target method is executed
*/
Object proceed() throws Throwable;
/**
* Returns the target object
*/
Object getThis();
/**
* Return to the target method
*/
AccessibleObject getStaticPart();
}

org.aopalliance.intercept.Invocation, Callers , By AOP An interface to the Alliance , as follows :

public interface Invocation extends Joinpoint {
/**
* Get parameter array
*/
Object[] getArguments();
}

MethodInvocation

org.aopalliance.intercept.MethodInvocation, Method caller , By AOP An interface to the Alliance , as follows :

public interface MethodInvocation extends Invocation {
/**
* Get the target method
*/
Method getMethod();
}

ProxyMethodInvocation

org.springframework.aop.ProxyMethodInvocation,MethodInvocation Extension of the method caller , Allow access to proxy objects , as follows :

public interface ProxyMethodInvocation extends MethodInvocation {
/**
* Return proxy object
*/
Object getProxy();
/**
* Cloning methods
*/
MethodInvocation invocableClone();
/**
* Cloning methods , Using parameter
*/
MethodInvocation invocableClone(Object... arguments);
/**
* Set parameter array
*/
void setArguments(Object... arguments);
/**
* Add custom properties
*/
void setUserAttribute(String key, @Nullable Object value);
/**
* Get custom properties
*/
@Nullable
Object getUserAttribute(String key);
}

Pointcut

Class diagram

  • AspectJExpressionPointcut, be based on AspectJ The ability to handle expressions is an important aspect of Pointcut, This paper does not analyze , In the following article to explain

The above class diagram only lists some Pointcut Associated interface

org.springframework.aop.Pointcut, Tangent point , Provide ClassFilter Class filters and MethodMatcher The method matcher supports class and method filtering , as follows :

public interface Pointcut {
/**
* Return to class filter
*/
ClassFilter getClassFilter();
/**
* Return method matcher
*/
MethodMatcher getMethodMatcher();
/**
* Always match through Pointcut Instance object
*/
Pointcut TRUE = TruePointcut.INSTANCE;
}

org.springframework.aop.support.ExpressionPointcut, Support expression matching Pointcut, as follows :

public interface ExpressionPointcut extends Pointcut {
/**
* Return expression
*/
@Nullable
String getExpression();
}

StaticMethodMatcherPointcut

org.springframework.aop.support.StaticMethodMatcherPointcut, abstract class , Itself is a method matcher Pointcut, as follows :

public abstract class StaticMethodMatcherPointcut extends StaticMethodMatcher implements Pointcut {
/** By default, class filters always match through */
private ClassFilter classFilter = ClassFilter.TRUE;
/**
* Set class filters
*/
public void setClassFilter(ClassFilter classFilter) {
this.classFilter = classFilter;
}
/**
* Get class filter
*/
@Override
public ClassFilter getClassFilter() {
return this.classFilter;
}
/**
* Return method matcher , Is the current object , Because the current object inherits StaticMethodMatcher It's just one. MethodMatcher
*/
@Override
public final MethodMatcher getMethodMatcher() {
return this;
}
}

We customize Pointcut You can usually inherit StaticMethodMatcherPointcut To achieve , rewrite MethodMatcher matches(Method method, Class<?> targetClass, Object... args) The method can , It can be realized again ClassFilter, Realization matches(Class clazz) Method

ClassFilter

org.springframework.aop.ClassFilter, Functional interface , Class filter , Used to judge this Class Is it satisfactory? Pointcut Tangent point , as follows :

@FunctionalInterface
public interface ClassFilter {
/**
* Match this Class class
*/
boolean matches(Class<?> clazz);
/**
* Always match passing class filters
*/
ClassFilter TRUE = TrueClassFilter.INSTANCE;
}

MethodMatcher

org.springframework.aop.MethodMatcher, Method matcher , Used to judge this Method Is it satisfactory? Pointcut Tangent point , as follows :

public interface MethodMatcher {
/**
* Match this method
*/
boolean matches(Method method, Class<?> targetClass);
/**
* Whether the current method matcher is running
*/
boolean isRuntime();
/**
* Match this method , And check the parameters
*/
boolean matches(Method method, Class<?> targetClass, Object... args);
/**
* Always match through the method matcher
*/
MethodMatcher TRUE = TrueMethodMatcher.INSTANCE;
}

Advice

Class diagram

  • Advice, Tag interface
  • BeforeAdvice, Tag interface , The rear notice
  • AfterAdvice, Tag interface , Pre notice
  • Interceptor, Tag interface , Interceptor
  • AbstractAspectJAdvice, Packed a Aspect Section or AspectJ How to annotate ,Around、Before、After、AfterReturning、AfterThrowing There are several types of Advice In the end, it's going to be AbstractAspectJAdvice Corresponding subclass and implement MethodInterceptor Method interceptor interface , This paper does not analyze , In the following article to explain

The above class diagram only lists some Advice Associated interface

MethodInterceptor

org.aopalliance.intercept.MethodInterceptor, method interceptors , Functional interface , as follows :

@FunctionalInterface
public interface MethodInterceptor extends Interceptor {
/**
* perform MethodInvocation Callers
*/
Object invoke(MethodInvocation invocation) throws Throwable;
}

Advisor

Class diagram

Only... Is listed above Advisor Part of the implementation class , stay Spring AOP There are also many implementation classes in , In the follow-up article analysis

  • AbstractBeanFactoryPointcutAdvisor, relation BeanFactory Of PointcutAdvisor abstract class , Support from the IoC Get... In the container Advice object , We can customize a by inheriting this class PointcutAdvisor object

org.springframework.aop.Advisor,Advice Container interface , And Advice It's a one-to-one relationship , as follows :

public interface Advisor {
/**
* Empty Advice
*/
Advice EMPTY_ADVICE = new Advice() {};
/**
* obtain Advice
*/
Advice getAdvice();
/**
* Go back to this Advice Whether there is a specified target instance object , The default is true
*/
boolean isPerInstance();
}

PointcutAdvisor

org.springframework.aop.PointcutAdvisor, Inherit Advisor Interface ,Pointcut and Advice The container of , take Pointcut Filter Joinpoint Ability and Advice Integration , That's how it connects the two , as follows :

public interface PointcutAdvisor extends Advisor {
/**
* obtain Pointcut Tangent point
*/
Pointcut getPointcut();
}

IntroductionAdvisor

org.springframework.aop.IntroductionAdvisor, Inherit Advisor and IntroductionInfo Interface , Support for proxy object implementation. The target class doesn't really implement additional interfaces ; adopt @DeclareParents The fields defined by the annotation are resolved to IntroductionAdvisor object , as follows :

public interface IntroductionAdvisor extends Advisor, IntroductionInfo {
/**
* Gets the class loader , Because no Pointcut Tangent point , Provides a class filter
*/
ClassFilter getClassFilter();
/**
* Verify that IntroductionInfo The interface
*/
void validateInterfaces() throws IllegalArgumentException;
}
public interface IntroductionInfo {
/**
* Return additional interfaces
*/
Class<?>[] getInterfaces();
}

AdvisorAdapter

Class diagram

org.springframework.aop.framework.adapter.AdvisorAdapter,Advisor Adapter for , When you filter out all the things that can be applied to the method Advisor after , You need to get the corresponding Advice; If not MethodInterceptor type , You have to go through AdvisorAdapter The adapter converts to the corresponding MethodInterceptor method interceptors , as follows :

public interface AdvisorAdapter {
/**
* Whether this type of Advice adapter
*/
boolean supportsAdvice(Advice advice);
/**
* obtain Advisor Of Advice, And packaged into the corresponding MethodInterceptor method interceptors
*/
MethodInterceptor getInterceptor(Advisor advisor);
}

org.springframework.aop.framework.adapter.MethodBeforeAdviceAdapter, In front of Advice Adapter for , as follows :

class MethodBeforeAdviceAdapter implements AdvisorAdapter, Serializable {
@Override
public boolean supportsAdvice(Advice advice) {
return (advice instanceof MethodBeforeAdvice);
}
@Override
public MethodInterceptor getInterceptor(Advisor advisor) {
MethodBeforeAdvice advice = (MethodBeforeAdvice) advisor.getAdvice();
return new MethodBeforeAdviceInterceptor(advice);
}
}

You can see this MethodBeforeAdviceAdapter The adapter can only be used in Spring For internal use , First judge Advice Is it MethodBeforeAdvice type , If so , Then you can put Advice Package as MethodBeforeAdviceInterceptor object , Other adapters are similar to .

Of course ,AdvisorAdapter The adapter is not used directly , But through DefaultAdvisorAdapterRegistry The adapter registry uses , In the follow-up article analysis

AOP Proxy object

Class diagram

org.springframework.aop.framework.AopProxy,AOP Proxy interface , Used to create a proxy object , as follows :

public interface AopProxy {
/**
* Create a proxy object
*/
Object getProxy();
/**
* Create a proxy object , Pass in the specified ClassLoader Class loader
*/
Object getProxy(@Nullable ClassLoader classLoader);
}

stay Spring AOP There is JdkDynamicAopProxy and CglibAopProxy Two implementation classes , Represent the JDK Dynamic proxy sum CGLIB A dynamic proxy . Choose which dynamic agent is through DefaultAopProxyFactory The agent factory is determined by the target class , These contents will be analyzed in the following article

AOP Agent configuration

Class diagram

org.springframework.aop.framework.ProxyConfig, Agent configuration class , as follows :

/**
* @see AdvisedSupport
*/
public class ProxyConfig implements Serializable {
/** use serialVersionUID from Spring 1.2 for interoperability. */
private static final long serialVersionUID = -8409359707199703185L;
/** Whether to use class proxy */
private boolean proxyTargetClass = false;
private boolean optimize = false;
boolean opaque = false;
/** Whether the proxy object is exposed */
boolean exposeProxy = false;
/** Whether the configuration is frozen */
private boolean frozen = false;
}

This class only provides some top-level configuration information , More configuration information about creating proxy objects is in subclasses AdvisedSupport in , These contents will be analyzed in the following article

AOP Proxy object creation

Class diagram

AOP The creation of proxy objects is divided into Manual mode and Automatic mode ; Either model is similar to AdvisedSupport Configuration manager ;

  • Manual mode It is through Spring AOP Provided API Create , for example ProxyFactory The agent factory ;
  • Automatic mode And Spring IoC Integration , stay Bean If proxy is needed during the loading process of , Then create the corresponding proxy object ; You can see AbstractAutoProxyCreator Realized BeanPostProcessor Related interfaces , In the load Bean In the process of , After initialization, it calls BeanPostProcessor#postProcessAfterInitialization Initialization post processing method of , stay AbstractAutoProxyCreator The corresponding proxy object can be created in ( If necessary )

Above these AOP The automatic proxy class will be analyzed in the following article

AOP Proxy target object source

Class diagram

org.springframework.aop.TargetSource, Target class source , Associate with a proxy object , Used to get the target object of the proxy , as follows :

public interface TargetSource extends TargetClassAware {
/**
* Get the target object's Class object
*/
@Override
@Nullable
Class<?> getTargetClass();
/**
* Whether it's static , return `fasle` It means that every time you get the target object, you need to create it , So each creation needs to release , For example, the prototype pattern of Bean
*/
boolean isStatic();
/**
* Get target object
*/
@Nullable
Object getTarget() throws Exception;
/**
* Release the target object
*/
void releaseTarget(Object target) throws Exception;
}

SingletonTargetSource

org.springframework.aop.target.SingletonTargetSource, Single case Bean The source of the target object , as follows :

public class SingletonTargetSource implements TargetSource, Serializable {
/** use serialVersionUID from Spring 1.2 for interoperability. */
private static final long serialVersionUID = 9031246629662423738L;
/** Save the target object */
private final Object target;
/**
* When you create an instance object, you set the target object
*/
public SingletonTargetSource(Object target) {
Assert.notNull(target, "Target object must not be null");
this.target = target;
}
@Override
public Class<?> getTargetClass() {
return this.target.getClass();
}
@Override
public Object getTarget() {
return this.target;
}
@Override
public void releaseTarget(Object target) {
// nothing to do
}
@Override
public boolean isStatic() {
return true;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof SingletonTargetSource)) {
return false;
}
SingletonTargetSource otherTargetSource = (SingletonTargetSource) other;
return this.target.equals(otherTargetSource.target);
}
@Override
public int hashCode() {
return this.target.hashCode();
}
@Override
public String toString() {
return "SingletonTargetSource for target object [" + ObjectUtils.identityToString(this.target) + "]";
}
}

Single case Bean Corresponding TargetSource All are SingletonTargetSource, It contains this single example Bean.

summary

The picture at the beginning of this article shows Spring AOP Most of the major ones involved are API, Around this picture, to these API Make a simple statement , Yes Spring AOP There can be a holistic understanding . however Spring AOP There's another part , How to open the whole AOP Module is not shown in this article , To put it briefly , adopt @EnableAspectJAutoProxy Note or <aop:aspectj-autoproxy /> XML Configuration can activate AOP modular , The bottom layer will register a AbstractAutoProxyCreator Type of Bean complete AOP Automatic agent , The specific process is analyzed in the following article

  • stay Spring AOP There is Joinpoint Connection point ,Pointcut Tangent point sum Advice notice , adopt Advisor The interface holds a Advice, Its sub interfaces PointcutAdvisor Another one Pointcut, take Pointcut Filter Joinpoint Ability and Advice Integration , That's how it connects the two .

  • Spring AOP Pass on Advice The process is usually through Advisor Realized , While using Advice It's all through MethodInterceptor perform , If it's not the type, it's through AdvisorAdapter The adapter packs it into the corresponding MethodInterceptor method interceptors .

  • Sping AOP At the bottom there is JDK Dynamic proxy sum CGLIB There are two ways of dynamic proxy , They correspond to each other JdkDynamicAopProxy and CglibAopProxy, To choose which way of agency needs to go through DefaultAopProxyFactory The agent factory decides according to the target class .

  • stay Spring AOP In a AdvisedSupport Configuration manager , It stores the configuration information of the corresponding proxy object , For example, if the conditions are met Advisor object 、TargetSource Target class source ,AdvisedSupport stay Spring AOP Play an important role in .

  • Spring AOP Medium Automatic agent Mainly by AbstractAutoProxyCreator This Bean Create , Because it implements several BeanPostProcessor, For example, in Bean During loading , After initialization, it calls AbstractAutoProxyCreator To deal with , Returns a proxy object ( If necessary ).

In the following articles, we mainly focus on Automatic agent Analyze , about Bean The loading process is not familiar with the small partner can see in front of me 《 screwing Spring And IoC piece - Article reading guidance 》 article , Or check it out 《 screwing Spring And IoC piece - Bean The creation process of 》 This article

版权声明
本文为[Full moon acridine]所创,转载请带上原文链接,感谢
https://javamana.com/2021/04/20210416132353820A.html

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云