Detailed Aop aspect programming

1. What is aspect-oriented programming (aop) and its application scenarios?
Compared with object-oriented programming (oop), the core unit of modularization in oop is the class, while the core unit of aop is the aspect. Aspects enable the modularization of concerns such as transaction management to be realized. Such as transaction management across multiple types and objects. Login token verification, method execution permission verification (access control), performance detection, transaction management, logging, etc.
2. Terminology of
aspect programming. Aspect (Aspetct): The relationship between the point of contact and the notification is called the
join point (Join Point). ): All methods in the class are connection points.
Point Cut: methods that lack common functional codes (the entry point must be the connection point, and the connection point is not necessarily the entry point)
Advice (some people call enhancement ): Define what the aspect wants to do, and the common code logic to be extracted. (Notifications are distinguished by location)
    Before notification (before),
    after notification (after),
    return notification (after-returning),
    abnormal notification (after-throwing),
    around notification (around)
introduction (Introduction): notifications can only extract common logic codes, Variables cannot be extracted. If you need to introduce variables into the pointcut method, you must use introduction. The introduction mechanism can be to add additional member variables or member methods to the class. The introduction mechanism is completed during the compiler or class loading period. (Understand)
Target Object: The object that lacks the common code, that is, the object that is separated from the common code (the target object is incomplete)
Proxy object (AOP Proxy): The proxy target object.
Weaving: At the point of entry, the proxy object weaves the notification into the target object, which is an action (springAop is weaving at runtime)
3. The relevant solution and configuration of aspect programming
@Aspect defines the aspect
@Pointcut defines the naming pointcut
    pointcut expression: execution (* cn.tedu.store.service.impl * * ( ..)..) && args (*)
            the first *: return any type
            second *: class
            third A*: The method in the class. The
            fourth (..): The method receives any type of parameter. The
            fifth*: The specified parameter
              execution ([method access control modifier] Method return value package name. Class name/interface Name. Method name (parameter)) 
              Note: The access control modifier of the method can be omitted, and the package name and class name must be included when writing the method name.
@Before defines the notification before the method is executed (application scenario: verification)
@After defines the notification after the method is executed (application scenario: clean up the site, release resources)
@AfterReturning defines the notification after the method execution result is returned (application scenario: regular data processing)
@AfterThrowing Define the notification after an exception is thrown in the execution of the method (application scenario: exception handling)
@Around can perform notification before and after the target method (application scenario: very powerful, you can do anything)
 


4. Case
4.1. Ways to obtain the parameters of the target method from the aspect: The
first method: obtain through the JoinPoint.getArgs() method of JoinPoint, which is the parent class of ProceedingJoinPoint.
The second type: add && args(*) through the entry point expression (the coupling is too high, it is not recommended)

4.2. Get the parameters of the target method and pass it to the target method after modification. Only ProceedingJoinPoint can be used, and only the around notification method can be used.

4.3. Ways to obtain the return value from the aspect: the
first: @AfterReturning(value = "pointCut()", returning = "res") (returning can be customized, but it must be consistent with the annotation method parameter name, which is Object res )
The second type: use the around notification, the return value of the ProceedingJoinPoint.proceed() method is the return value of the target method (note: when ProceedingJoinPoint returns the return value of the target object, the return method type must be consistent with the target method return type)

4.4. The method of obtaining the throwing exception information from the 
 aspect: @AfterThrowing(value = "pointCut()", throwing = "e") (throwing can be customized, but it must be consistent with the annotation method parameter name, which is Throwable e)


5. Aop proxy
Aop proxy is divided into static proxy and dynamic proxy. The representative of static proxy is AspectJ, and the representative of dynamic proxy is springAop.
The so-called dynamic proxy means that the aop framework does not modify the bytecode, but temporarily generates an Aop object for the method in the memory (we can call it a "proxy object"), this Aop object contains all of the target object Method, and enhanced processing at a specific point of contact, and callback methods of the original object.

There are two main ways of dynamic proxy in springAop: JDK dynamic proxy and CGLIB dynamic proxy
5.1. JDK dynamic proxy is a class that receives proxy through reflection, and requires the proxy class to implement an interface. The core of the JDK dynamic proxy is the IncocationHandler interface and the Proxy class. Now we are all interface-oriented programming, and the projects we do are all kinds of interfaces + implementation classes. Therefore, there are interfaces and implementation classes in a spring project. If they are not specially configured in the spring configuration file (that is, the default configuration is used), the default proxy method is JDK dynamic proxy. But if the target class does not implement the interface, then springAOP will choose to use CGLIB to dynamically power the target class.

5.2. CGLIB (Code Generation Library) is a class library for code generation, which can dynamically generate a subclass of a certain class at runtime, that is, after compilation, by modifying the bytecode, a new proxy object proxyObj is generated. Note that CGLIB is a dynamic proxy through inheritance. Therefore, if a class is marked as final, it cannot use CGLIB as a dynamic proxy.


Example:
JDK dynamic proxy: The
target class (implementation class) can be considered as chef Zhang San, and Zhang San can implement all the functions of the interface. For example, the boss can let Zhang San cook. When aop agent, it will be implemented according to Zhang San. Create a Zhang San A (agent object) as Zhang San’s avatar. At this time, Zhang San and Zhang San A have the same interface (dynamic embodiment), and the two look exactly the same. At this time, Zhang San A can Wash the dishes before Zhang San cooks, and then Zhang San himself will cook. But in the eyes of the boss (caller), Zhang San (the target class) alone was washing vegetables and cooking from beginning to end. But Zhang San (target class) knows that his surrogate helped him do some things before he started cooking, and similarly, the surrogate can help him wash the dishes after he cooks dinner himself.
Therefore, if the target class does not implement the interface, the program cannot implement a proxy object based on the interface, and it cannot replace the target class (implementation class) to do something. This proxy method is effective only when the method is called through the interface.

CGLIB dynamic agency:
We compare the target analogy to Li Gang. When acting, the program will create a subclass based on Li Gang to inherit the target class. Then this subclass is the proxy object (Li Gang’s son), so Li Gang’s son can replace his dad. Money (because his dad is Li Gang, haha), because of polymorphism, the program can't recognize it, and then when the target class is doing things for others, in the eyes of outsiders, it is Li Gang who is collecting money to do things. But Li Gang has a lot of privileges. His son has no authority, that is, there are final methods in the target class, and subclasses cannot inherit, so the proxy object cannot proxy this part of the function. (It stands to reason that the final modification method can be inherited, but it cannot be overridden. It is said that CDLIB cannot proxy this part of the function of the parent class. Guess: In fact, the final modification method can be inherited, but it cannot be overridden. That is, it cannot be subclassed concretely. Em can be understood as other methods can be directly rewritten, and then pointcut enhancements can be made through the rewritten method, and proceed() will be called back when the method of the target class is executed. So it is final The method cannot find an entry point, so naturally it cannot be enhanced.)


Develop AOP based on annotations:
The execution order between different annotations is fixed:
around before
before
around after
after
afterReturning

The execution order between the same annotations is not fixed and is affected by the method name and position, so if the program is related to the execution order, it is recommended to use the xml configuration

The premise of the JDK dynamic proxy is that the interface
jdk dynamic proxy must be implemented. In fact, the newProxyInstance method of the java.lang.reflect.Proxy class is used to implement the dynamic proxy.

Similar to inherit the
CGLIB dynamic proxy: the full name (Code Generation Library), is a class library for code generation, which can dynamically generate bytecode objects. 
CGLIB implements dynamic proxy steps:
1. Generate a bytecode object (empty) out of thin air
2. Settings The parent class of the bytecode object is the target object
3. Callback methods are performed through the generated bytecode object, and the target method is enhanced during the callback process (enhancement of method functions)
4. Create proxy object (complete dynamic proxy)
call The method function of the proxy object is enhanced

CGLIB is a third-party, but it has been integrated into the core jar package of spring.

JDK dynamic proxy (agent for objects)
CGLIB dynamic proxy (agent for (class) bytecode)

idea View the shortcut keys of an interface's sub-interface or implementation class:
first select the class or interface, and then press Ctrl + h
 

 

Guess you like

Origin blog.csdn.net/D_J1224/article/details/108362494