Let’s learn SF framework series 7.1-spring-AOP-basic knowledge together

AOP (Aspect-oriented Programming) is a programming model that is a useful supplement to OOP (Object-oriented Programming). In OOP, everything is an independent object, and the coupling relationship between objects is based on business; but in actual application systems, there are public management requirements for a large number of objects (such as functional safety checks, logging, method execution time statistics etc.), these behaviors have nothing to do with the industry itself, so it is difficult to deal with the object itself. This is the reason for the birth and development of AOP.

basic concept

The goal of AOP is to complete one or several common behavioral logics before or after certain methods are executed. The schematic diagram is as follows:
Insert image description here

The icons with red borders in the picture form a complete AOP (only shown before the method, but also after the method):
Logging: This is the goal of AOP - logging when the corresponding method is executed. Corresponds to the aspect in AOP.
Red line: represents the cut-in position of the aspect (log record). The blue square of the Joinpoint corresponding to the AOP concept
: represents the conditions under which aspects (logging) really work. The red arrow corresponding to the pointcut of the AOP concept
: represents the notification to initiate execution. Advice corresponding to AOP concepts

the term

Aspect : refers to the common business that needs to be processed. An aspect is a common business. For example, functional safety verification is one aspect, and logging is another aspect. When implemented, the class that handles the business usually represents an aspect. (In Chinese, "aspect" is more accurate and vivid than "aspect", which means to do something before and after cutting into the method)
Joinpoint : The position where the aspect needs to work during program execution, usually the method of the object.
Advice : An action taken by an aspect at a specific join point. It can be more straightforwardly understood as executing the corresponding method of the aspect according to the notification type when the program is executed to the connection point. There are five types of notifications (see below).
Pointcut : Defines an expression that matches a join point. Advice is associated with a pointcut expression and is run at any join point that the pointcut matches (for example, executing a method with a specific name). The join point concept of pointcut expression matching is the core of AOP, and Spring uses the AspectJ pointcut expression language by default.
Introduction : Declares other methods or fields on behalf of the type. Spring AOP allows you to introduce new interfaces (and corresponding implementations) to any advised object. For example, you can use quotes to make beans implement the IsModified interface to simplify caching.
Target Object : An object notified by one or more aspects, that is, a business logic object related to aspect notification in the application.
Proxy Object : It is an object generated after using aspect logic to wrap business logic.
AOP proxy(AOP proxy): An object created by the AOP framework, used to implement the aspect contract (such as notification method execution, etc.). In Spring Framework, the AOP proxy is a JDK dynamic proxy or a CGLIB proxy.
Weaving : Linking aspects with application types or objects to create notification objects. Typically this is done by the framework at compile time, load time or run time. Spring AOP performs weaving at runtime.

Note: The difference between the target object and the proxy object :
the target object is the business logic object we declare, while the proxy object is the object generated after using aspect logic to wrap the business logic. If you are using a Jdk dynamic proxy, then the business object and the proxy object will be two objects. When calling the proxy object logic, the logic of the target object will be called in its aspect logic; if you are using a Cglib proxy, since you are using a sub- If the class is woven with aspect logic, then there will be only one object, that is, the subclass object of the business class with proxy logic woven into it. At this time, no business class object will be generated.

notification type

Before advice : Advice that runs before the join point is executed and cannot prevent execution flow from continuing to the join point (unless an exception is thrown).
After returning advice : Advice that runs after normal execution of the join point has completed (for example, if a method returns without throwing an exception).
After throwing advice : Advice to run if the method exits by throwing an exception.
After (finally) advice : Advice that runs regardless of how the connection point exits (normal or exception return).
Around advice : Advice around join points (such as method calls). Around advice must run corresponding advice before and after method execution. It is also responsible for choosing whether to continue to the join point or shorten the execution of the advice method by returning its own return value or throwing an exception.

Notification execution order

If multiple advices appear in the same Joinpoint, the execution order is: Around’s before advice–>Before advice–>(AfterThrowing advice)–>AfterReturn advice–>After advice–>Around’s after advice.
Note : If AfterThrowing advice occurs, subsequent After Advice will be executed, and other Advice will no longer be executed.

AOP application scenarios

  1. Logging: Record information such as the input parameters and output parameters of the method, as well as the execution time of the method;
  2. Security check: authenticate the user before executing the method to determine whether he or she has the authority to access the method;
  3. Performance monitoring: Record the calling frequency and execution time of methods to facilitate analysis of program performance bottlenecks;
  4. Transaction management: start a transaction before the method is executed, and commit or rollback the transaction according to the method execution result after the method is executed;
  5. Cache: Determine whether the result of the method exists in the cache before the method is executed, and store the result in the cache after the method is executed to facilitate the next call.
  6. Unified return parameter format: front-end and back-end parameters can be unified
  7. Exception handling: Exceptions can be managed uniformly.

AOP implementation mechanism

AOP is implemented through a proxy mechanism.

What is an agent

  The essence of "agency" is that A wants to complete something, and B can do it on behalf of A. The effect of both is that the result is the same, but the process may be different. For example, if I want to register a company, I definitely need to obtain a business license. If I apply for it myself, I will easily fall into the trap and the efficiency will be very low. I can entrust an intermediary (agent) to help me complete it. Their process of applying for the certificate is definitely different from the process of doing it myself. But the ultimate goal is to obtain a business license. Technically speaking, achieving the same result means that the method itself can be directly executed, while the different process means that other things can be done before or after the method is executed. The schematic diagram of the proxy mechanism is as follows:
Insert image description here
It can be seen from the figure that the difference between before and after proxy is that the method is encapsulated by the proxy (automatically performed by the framework):
1. From the perspective of the coder, there is no difference between the two, both are direct Call method.
2. From a machine perspective (executed after compilation), the call is actually completed by the agent, and the agent also does its own thing (otherwise there is no need to add an agent).
3. Judging from the results, the results obtained by 1 and 2 are the same.

  In Java, the reasons for introducing dynamic proxies are as follows:
  1. Dynamic proxies are mainly used to enhance methods, allowing you to enhance some methods without modifying the source code, and do whatever you want before and after the method is executed ( Even do not execute this method at all), such as adding call logs, doing transaction control, etc. A typical application is AOP.
  2. Application decoupling: Through dynamic proxies, the relationship between applications becomes loose, thereby better achieving decoupling. For example, if two systems communicate via RMI, each system must use the same message structure and specification. Dynamic proxies allow mapping between different message structures and specifications to complete communication between two systems.
  3. Optimize performance: When calling a remote service or local database, a connection or transaction needs to be established. Using a dynamic proxy avoids expensive connection and transaction management operations on every request. For example, the ORM framework uses dynamic proxies to map Java objects to database tables.

technical mechanism

  The proxy class and the proxy class implement a common interface (or inheritance). The proxy class contains an index pointing to the proxy class. During actual execution, the method of the proxy class is called, and the method of the proxy class is actually executed.

Implementation model

  There are two common implementation modes of agents: static agents and dynamic agents.
  Static proxy is a compile-time enhancement. The framework will generate a proxy class during the compilation phase. The .class file of the proxy class already exists before the program is run. Common implementations: JDK static proxy, AspectJ.
  Dynamic proxy is a runtime enhancement. It does not modify the bytecode of the proxy class. Instead, it uses the reflection mechanism to temporarily generate a proxy object for the method in the memory when the program is running. This proxy object contains all the methods of the target object. , and enhanced processing is done at specific cut points, and the method of the original object is called back. Common implementations: JDK, CGLIB, Javassist (using dynamic proxy in Hibernate)

CGLIB

  GLIB is mainly an open source project proposed to enhance the dynamic proxy function. Technically, it is to dynamically generate a subclass to cover the class to be proxied (non-final modified classes and methods).
  CGLIB is mainly used in AOP, testing, data access and other frameworks.
  The bottom layer of CGLIB uses ASM (a short and concise bytecode manipulation framework) to manipulate bytecodes to generate new classes.
  CGLIB is an open source project, and its code is hosted on github: https://github.com/cglib/cglib .

The difference between JDK proxy and CGLIB

1. JDK proxy can only proxy interfaces, not ordinary classes (because the parent class of all generated proxy classes is Proxy, and the Java class inheritance mechanism does not allow multiple inheritance); CGLIB can proxy ordinary classes, but is proxied Classes cannot be final or have final methods.
2. The JDK agent uses Java's native reflection API to operate, and the class generation is more efficient; CGLIB uses the ASM framework to directly operate the bytecode, and the class execution process is more efficient.
3. The JDK proxy needs to write its own proxy class, and the proxy class needs to implement the same interface as the target object. CGLIB does not need to write proxy classes by itself, proxy classes are dynamically generated.

Spring AOP proxy

SpringAOP uses the standard JDK dynamic proxy as the AOP proxy by default. This allows any interface (or set of interfaces) to be proxied. Spring AOP can also use a CGLIB proxy, which is used if the business object does not implement the interface.

Spring AOP features and goals

1. Spring AOP is implemented in pure Java. Spring AOP does not require control of the class loader hierarchy, making it suitable for use in servlet containers or application servers.
2. Spring AOP currently only supports method execution connection points (it is recommended to execute methods on Spring Bean). Although support for field interception could be added, field interception is not implemented. If necessary, consider using AspectJ.
3. Spring AOP’s AOP approach is different from most other AOP frameworks. Its purpose is not to provide the most complete AOP implementation (although Spring AOP is very powerful). Instead, its purpose is to provide tight integration between AOP implementations and SpringIoC to help solve common problems in enterprise applications. Therefore, Spring Framework's AOP functionality is often used with the Spring IoC container. Features are configured using normal bean definition syntax, which is a key difference from other AOP implementations. There are some things you can't do easily or efficiently with SpringAOP, such as notifying very fine-grained objects (usually domain objects). In this case, AspectJ is the best choice.
4. The purpose of Spring AOP is not to compete with AspectJ to provide a comprehensive AOP solution. They are complementary, not competitive. Spring AOP and IoC can be seamlessly integrated with AspectJ to enable all uses of AOP within a consistent Spring-based application architecture.

Additional notes :
1. One of the core principles of the Spring framework is non-intrusiveness. Just the idea of ​​not forcing you to introduce framework-specific classes and interfaces into your business or domain model. However, in some places, Spring Framework does give you the option to introduce Spring Framework-specific dependencies into your codebase. The rationale for providing these options is that in some cases it may be easier to read or code certain functions this way. Regardless, Spring Framework always gives you options: you are free to make an informed decision about which option is best for your specific use case or scenario. Therefore, you can choose which AOP framework to use: AspectJ, SpringAOP, or both. You can also choose @AspectJ annotation style methods or SpringXML configuration style methods.
2. How to choose Spring AOP or AspectJ for an application? Selection principle: Use the simplest feasible method. SpringAOP is simpler than using full AspectJ because there is no need to introduce AspectJcompiler/weaver in the development and build process. If you only need to perform operations on Spring-managed beans, SpringAOP is the right choice. If you need to notify objects that are not managed by the Spring container (usually domain objects), you need to use AspectJ. You also need to use AspectJ if you wish to suggest join points instead of simple method execution (e.g. field get or set join points, etc.).

Guess you like

Origin blog.csdn.net/davidwkx/article/details/131715756