Analysis of spring AOP implementation principle
What is AOP
AOP (aspect oriented programming) can be called OOP (object-oriented programming). OOP introduces the concepts of encapsulation, inheritance and polymorphism to establish an object hierarchy to simulate a collection of public behaviors. When we need to introduce public behaviors for decentralized objects, OOP is powerless. That is, OOP allows you to define top-down relationships, but It is not appropriate to define a left to right relationship. For example, log function. Log code is often spread horizontally across all object levels, regardless of the core functions of the objects it spreads. The same is true for other types of code, such as security, exception handling, and transparent persistence. This kind of irrelevant code scattered everywhere is called cross cutting code. In OOP design, it leads to a large number of code duplication, which is not conducive to the reuse of each module.
On the contrary, AOP technology uses a technology called "crosscutting" to dissect the interior of encapsulated objects, encapsulate the public behaviors that affect multiple classes into a reusable module, and call it "aspect", that is, aspect. The so-called "aspect", in short, is to encapsulate the logic or responsibilities that have nothing to do with the business but are jointly called by the business modules, so as to reduce the repeated code of the system, reduce the coupling degree between modules, and facilitate the operability and maintainability in the future. AOP represents a horizontal relationship. If an "object" is a hollow cylinder, it encapsulates the attributes and behavior of the object; Then the aspect oriented programming method is like a sharp blade to cut open these hollow cylinders to obtain their internal messages. The cut section is the so-called "aspect". Then it restored these cut sections without leaving any trace with its skillful hand of seizing heavenly power.
Using "crosscutting" technology, AOP divides the software system into two parts: core concerns and crosscutting concerns. The main process of business processing is the core concern, and the part that has little to do with it is the crosscutting concern. A characteristic of crosscutting concerns is that they often occur in multiple parts of the core concerns, and they are basically similar everywhere. Such as authority authentication, logging, and transaction processing. The role of AOP is to separate various concerns in the system and separate the core concerns from the crosscutting concerns. As Adam Magee, senior solution architect of avanade, said, the core idea of AOP is to "separate the business logic in the application from the common services that support it."
The technologies to realize AOP are mainly divided into two categories: one is to use dynamic agent technology to decorate the message by intercepting the message to replace the execution of the original object behavior; The second is to use static weaving and introduce specific syntax to create "aspects", so that the compiler can weave the code related to "aspects" during compilation.
AOP usage scenarios
AOP is used to encapsulate crosscutting concerns, which can be used in the following scenarios:
Authentication permissions caching context passing content passing error handling lazy loading debugging logging, tracing, Profiling and monitoring record tracking optimization calibration performance optimization persistence persistence persistence resource pool synchronization synchronous transactions
AOP related concepts
Aspect: modularization of a concern, which may crosscut multiple objects. Transaction management is a good example of crosscutting concerns in J2EE applications. Aspects are implemented with spring's advisor or interceptor.
Join point: a specific point in the process of program execution, such as the call of a method or the throwing of a specific exception.
Advice: the actions performed by the AOP framework at a specific connection point. Various types of notifications include "around", "before" and "throws" notifications. The types of notifications will be discussed below. Many AOP frameworks, including spring, use interceptors as notification models to maintain a "around" Interceptor chain of connection points. Spring defines four advice: before advice, after advice, throw advice and dynamic introduction advice
breakthrough point (pointcut): specifies a collection of a series of connection points that will be triggered by a notification. The AOP framework must allow developers to specify pointcuts: for example, using regular expressions. Spring defines a pointcut interface to combine methodmatcher and classfilter. It can be clearly understood from the name. Methodmatcher is used to check whether the methods of the target class can be applied Classfilter is used to check whether pointcut should be applied to the target class
introduce (Introduction): add methods or fields to the notified class. Spring allows the introduction of new interfaces to any notified object. For example, you can use an introduction to make any object implement the ismodified interface to simplify caching. To use introduction in spring, you can implement notification through delegatingintroductioninterceptor and through defaultintroductionadvisor Configure the interfaces to be implemented by the advice and proxy classes
Target object: an object that contains connection points. Also known as a notified or proxied object. POJO
AOP proxy: an object created by the AOP framework and containing notifications. In spring, AOP proxy can be JDK dynamic proxy or cglib proxy.
Weaving: assemble aspects to create a notified object. This can be done at compile time (for example, using the AspectJ compiler) or at run time. Spring, like other pure Java AOP frameworks, completes weaving at run time.
Spring AOP components
The following class diagram lists the main AOP components in spring
How to use spring AOP
Spring AOP can be used through configuration files or programmatically.
Configuration can be done through XML files in four ways: 1 Configure proxyfactory bean and explicitly set advisors, advice, target, etc. 2 Configure autoproxycreator. In this way, the defined bean is still used as before, but the proxy object obtained from the container is actually 3 Configure 4.0 through < AOP: config > Configure through < AOP: AspectJ AutoProxy >, and use AspectJ annotations to identify notifications and pointcuts
You can also directly use proxyfactory to programmatically use spring AOP. You can set the target object, advisor and other related configurations through the methods provided by proxyfactory, and finally obtain the proxy object through the getproxy () method
Specific examples can be Google. Com Omit here
Generation of spring AOP proxy object
Spring provides two ways to generate proxy objects: jdkproxy and cglib. The specific way to generate proxy objects is determined by aopproxyfactory according to the configuration of the advised support object. The default policy is to use JDK dynamic proxy technology if the target class is an interface, otherwise use cglib to generate a proxy. Let's study how spring uses JDK to generate proxy objects. The specific generation code is placed in the class jdkdynamicaopproxy, which is directly related to the relevant code:
In fact, this is very clear. I have written it clearly in the notes, so I won't repeat it.
The following question is, when the proxy object is generated, how is the section woven? We know that invocationhandler is the core of JDK dynamic proxy, and the method calls of generated proxy objects will be delegated to invocationhandler Invoke() method. Through the signature of jdkdynamicaopproxy, we can see that this class actually implements invocationhandler. Next, we will see how spring AOP is woven into the aspect by analyzing the invoke () method implemented in this class.
The main process can be briefly described as: obtain the interceptor chain that can be applied to this method. If yes, apply the notification and execute the joinpoint; if not, directly reflect and execute the joinpoint. The key here is how to obtain the notification chain and how it is executed. Let's analyze it one by one.
First, you can see from the above code that the notification chain is through advised Getinterceptorsanddynamicinception advice() method. Let's look at the implementation of this method:
You can see that the actual acquisition is actually done by advisor chainfactory Getinterceptorsanddynamicinception advice() method, and the obtained results will be cached.
Let's analyze the implementation of this method:
After this method is executed, all the advisors configured in advised that can be applied to the connection point or target class are converted into methodinterceptor
Next, let's look at how the interceptor chain works.
It can be seen from this code that if the obtained interceptor chain is empty, the target method will be called directly. Otherwise, create a methodinvocation and call its processed method to trigger the execution of the interceptor chain. Let's see the specific code below
The code is also relatively simple, which will not be repeated here.
The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.