Spring_ Implementation mechanism of AOP - dynamic agent

1. AOP of spring core

1.1 concept of AOP

AOP is aspect oriented programming, that is, aspect oriented programming.
Function of AOP: enhance the function of the method during program operation without modifying the source code
In development: do what they are good at, and weave the service code into the core business when running.
Through the spring factory, the service code is automatically added to the core business code in a faceted way.

1.2 AOP related terms

Target (target object)
The object to be enhanced is generally the object of business logic class.

Proxy
After a class is woven and enhanced by AOP, a result proxy class is generated.

Aspect
It refers to an enhanced function, which is a function completed by some code, not a business function. It is the combination of entry point and notification.

Joinpoint
The so-called connection points refer to those intercepted points. In Spring, these points refer to methods (generally business methods in classes), because Spring only supports connection points of method types.

Pointcut
A pointcut is a collection of one or more declared join points. Specify a set of methods through pointcuts. Methods marked final cannot be used as join points and pointcuts. Because the final can not be modified, can not be enhanced.

Advice (notification / enhancement)
The so-called notification refers to what needs to be done after intercepting the Joinpoint. The notification defines the time point when the enhanced code cuts into the target code, whether it is executed before or after the execution of the target method. Different notification types lead to different cut in times.

Weaving
Refers to the process of applying enhancements to the target object to create a new proxy object. spring uses dynamic proxy weaving, while AspectJ uses compile time weaving and class loading time weaving.

2. Implementation of AOP by AspectJ

2.1 notification type of AspectJ

AspectJ There are five types of notifications commonly used in:
  Advance notice( Before): The notification function is invoked before the target method is invoked.
  Post notification( After): Call the notification after the target method is completed, and it will not care what the output of the method is.
  Return notification( After-returning): Call notification after successful execution of the target method;
  Exception notification( After-throwing): Call the notification after the target method throws an exception.
  Surround notification( Around): The notification wraps the notified method and performs custom behavior before and after the notified method is called.

2.2 pointcut expression of AspectJ


The above expression consists of four parts.
Execution (access permission method return value method declaration (parameter) exception type).
The object to be matched by the pointcut expression is the method name of the target method. Therefore, the execution expression is the signature of the method.
Examples

execution(* com.kkb.service.*.*(..))
The specified pointcut is: defined in service Any method of any class in the package.

execution(* com.kkb.service..*.*(..))
The specified pointcut is: defined in service Any method of any class in a package or sub package. “.."When it appears in the class name, it must be followed by“*",Represents all classes under package and sub package.

execution(* com.kkb.service.IUserService+.*(..))
The specified entry point is: IUserService If it is an interface, it is any method in the interface and any method in all its implementation classes; If it is a class, it is any method in the class and its subclasses.

2.3 code examples

1 target class

//Target class
public class SomeServiceImpl{
    public void doThird() {
        System.out.println("Business execution method doThird()");
    }
}

2 aspect class: it is a class used to add functions to business methods. In this class, there are aspect function codes

/**
 * @Aspect : Is an annotation in the aspectj framework
 *      Function: indicates that the current class is a faceted class
 *      Aspect class: a class used to add functions to business methods. In this class, there are aspect function codes
 */
@Aspect
public class MyAspect {

    @After(value = "myPointcut()")
    public void myAfter(){
        System.out.println("Code that will always be executed when the final notification is executed");
    }

    @Before(value = "myPointcut()")
    public void myBefore(){
        System.out.println("Pre notification is executed before the target method is executed");
    }

    /**
     * @Pointcut : Define and manage pointcuts. If multiple pointcut expressions in the project are repeated, they can be reused
     *
     * Features: use @ Pointcut to define on the method. The name of this method is the alias of the Pointcut expression. In other notifications, the value attribute can use this method name instead of the Pointcut expression
     *              stay
     */
    @Pointcut(value = "execution(* *..SomeServiceImpl.doThird(..))")
    public void myPointcut(){
        //No code required
    }
}

3 static agent

/**
 Advantages and disadvantages of static proxy class
	 Advantages: business classes only need to pay attention to the business logic itself, which ensures the reusability of business classes. This is a common advantage of agents.
	 Disadvantages:
		 1)An interface of proxy object only serves one type of object. If there are many methods to proxy, it is bound to proxy for each method. Static proxy is not competent when the program scale is slightly large.
		 2)If a method is added to the interface, all proxy classes need to implement this method in addition to all implementation classes. It increases the complexity of code maintenance.
 */

1: Here is an example of going to the cinema

public interface Movie {
    //watch movie
    void play();
}

2. RealMovie is an implementation class

/**
 * Core business, only watching movies
 */
public class RealMovie implements Movie {
    @Override
    public void play() {
        System.out.println("You are watching the movie shawshank redemption");
    }
}

3: Cinema is a proxy class

/**
 * proxy class
 */
public class Cinema implements Movie {

    private RealMovie movie;
    //Agent role
    public Cinema(RealMovie movie) {
        super();
        this.movie = movie;
    }

    @Override
    public void play() {
        guanggao(true);(Service oriented business)
        //You watch movies (the core business is watching movies)
        movie.play();(Service oriented business)
        guanggao(false);
    }
    //Subsidiary operation of intermediary (Cinema)
    public void guanggao(boolean isStart){
        if ( isStart ) {
            System.out.println("The movie starts right away. Popcorn, coke and gum 9.8 Discount, come and buy it!");
        } else {
            System.out.println("The movie is over soon. Popcorn, coke and gum 8.8 Discount, buy and eat at home!");
        }
    }

}

4: Test class

public class ProxyTest {

    public static void main(String[] args) {
        RealMovie realmovie = new RealMovie();

        //Agent, the mediation will also add some subsidiary operations
        Movie movie = new Cinema(realmovie);
        movie.play();
    }
}

5: Console output

The movie starts right away. Popcorn, coke and gum 9.8 Discount, come and buy it!
You are watching the movie shawshank redemption
 The movie is over soon. Popcorn, coke and gum 8.8 Discount, buy and eat at home!

4 implementation mechanism of AOP - dynamic agent

4.1 JDK dynamic agent

/**
 *  Interface based dynamic proxy: implement InvocationHandler interface - > call handler proxy - > proxy
 *
 * The specific steps are:
 * a. Implement the InvocationHandler interface to create your own calling processor
 * b. Provide ClassLoader and Proxy interface type array for Proxy class to create dynamic Proxy class
 * c. Taking the calling processor type as the parameter, the constructor of the dynamic proxy class is obtained by using the reflection mechanism
 * d. Taking the calling processor object as the parameter, the dynamic proxy class object is created by using the constructor of the dynamic proxy class
 *
 * Benefits: a dynamic proxy class can proxy multiple classes as long as it implements the same interface; High reusability
 *
 */

JDK dynamic Proxy mainly involves Java Two classes in lang.reflect package: Proxy and InvocationHandler. InvocationHandler is an interface that defines the crosscutting logic by implementing the interface, and calls the code of the target class through the reflection mechanism to dynamically compile the crosscutting logic and business logic together.
Proxy uses InvocationHandler to dynamically create an instance that conforms to an interface and generate the proxy object of the target class.

4.2 Cglib dynamic agent

Cglib proxy, also known as subclass proxy. Build a subclass object in memory to expand the function of the target object.
One limitation of DK's dynamic proxy is that the object using dynamic proxy must implement one or more interfaces. If you want to proxy a class that does not implement an interface, you can use CGLIB implementation.

5 difference between static agent and dynamic agent

1 static proxy usually only proxies one class, while dynamic proxy is to proxy multiple implementation classes under one interface.
2 the static agent knows what to proxy in advance, while the dynamic agent does not know what to proxy. It only knows when it is running.
3 static agent, before the program runs, the agent class Class file already exists; Dynamic agent is created dynamically by using reflection mechanism when the program is running.

6 difference between two dynamic proxy methods

1. JDK dynamic agent can only generate agents for classes that implement interfaces, not for classes; Cglib implements a proxy for a class. It mainly generates a subclass of a specified class and overrides the methods in it. Because it is inheritance, it is better not to declare this class or method as final.
2 Cglib a target class method will generate two proxy methods, one rewrites the target method and implements the proxy logic, and the other directly calls the target class method.

Finally, if there are problems, I hope to correct them and make progress together.

Keywords: Java Spring AOP

Added by baw on Mon, 31 Jan 2022 00:05:17 +0200