[Classic Detailed] AOP in Spring (Aspect Oriented Programming)

After reading this AOP blog post, you will learn the following:

table of Contents

 

1. What is AOP?

2. The underlying principle of AOP

3. Terminology of AOP Operation

4. AOP specific operations

to sum up:


1. What is AOP?

  (1) AOP is aspect-oriented programming, a continuation of OOP (object-oriented programming). AOP can isolate the various parts of the business, thereby reducing the coupling between the various parts of the business logic, improving the reusability of the program, and improving the efficiency of development.

  (2) In layman's terms: The main function of AOP is to enhance the main functions without modifying the source code.

    The following is a login function. Now I want to add a permission function without modifying the source code under the condition of a login.

    If you add a function, AOP can write another module, which has low coupling with the current login module and strong independence. 

2. The underlying principle of AOP

  Regarding the underlying principle, Spring 5 has already encapsulated the dynamic proxy, and only a simple configuration is required when using it.

   The bottom layer of AOP uses a dynamic proxy model, and there are two cases of dynamic proxy.

   The first is the case with an interface, and the JDK dynamic proxy is used. The second is the case without an interface, and the CGLIB dynamic proxy is used.

     ①There are interfaces, and the dynamic proxy of JDK is used, or UserService, UserDao, UserDaoImpl as examples.

   The so-called proxy object is the proxy object of the enhanced object, and the function is enhanced through the proxy object.

   Create a proxy object of the UserDao interface implementation class, enhance the methods in the class through the proxy object, add some new functions through the proxy object, proxy the UserDaoImpl class, and enhance the methods in the UserDaoImpl implementation class through the proxy object to add some new functions.

  

   An implementation class with an interface uses JDK dynamic proxy and uses the methods in the Proxy class to create proxy objects.

  

The parameters in newProxyInstance(...) are as follows:

(1) ClassLoader loader: class loader, this class is the class of the current proxy object

(2) <?>[] interfaces: The interface implemented by the class where the enhanced method is located is the interface where the enhanced method is located, supporting multiple interfaces

(3) InvocationHandler h: implement this interface InvocationHandler, create proxy objects, and write enhanced methods

Steps to write code:

  <1>Create interface, define method

 <2>Create interface implementation class and implementation method

 <3>Use the Proxy class to create an interface proxy object

Each class has an object of the Class class, that is, when we write a class, after the class file is generated, a Class object will be generated to represent the type information of this class. A method to obtain the Class class:

 <1>Using the object to call the getClass() method to obtain the Class instance of the object of this class

 <2>Use the static method forName() of Class, fill in the class, and use the name of the class to obtain an instance of the Class class

 <3>Use the class name.class method to obtain an instance of Class

②There is no interface, using CGLIB dynamic proxy, with User as the parent class and Person as the subclass. Create dynamic proxy mode

   The proxy object of the User subclass Person, which enhances the methods in the subclass.

The above is the underlying principle of AOP. The underlying principle only needs to know how the function is enhanced. Spring has already encapsulated the bottom layer, the following is the configuration in the project development.

3. Terminology of AOP Operation

 Terminology is generally more professional.

Example: If there is a User class, there are 4 methods in the class.

Class User{
    add();
    update();
    select();
    delete();
}

 AOP has 4 operating terms:

  ① Connection point:

  Which methods in the class can be enhanced, these methods are called connection points.

  ② Entry point:

  If there are 4 methods in the class that can be enhanced theoretically, the method that is actually enhanced is called the entry point.

  ③Notice (enhanced):

    (1) If the enhancement is the add() method, and you want to do some other operations after the add method is executed, the logic to implement the enhancement is called notification.

   Example: The authorization judgment is added during the login process. The whole process of authorization judgment is called notification, and the added part is called logic enhancement.

    (2) There are many types of notifications

    *Pre-notification: @Before, executed before the enhancement method

    *Post notification: @After, the enhanced method will be executed after

    *Around notification: @Around, execute both before and after the enhancement method

    *Exception notification: When the enhancement method is abnormal, it will be executed

    *Final notice: it is equivalent to finally in the exception, which will always be executed

  ④Cut noodles

  It is an action process. The process of applying notification to the point of entry is called notification. For example, the process of implementing authorization operations during the login process and the process of adding authorization judgment to the login method is called the aspect.

4. AOP specific operations

   ①The operation of AOP is generally implemented in the Spring framework based on AspectJ

   AspectJ is not a part of Spring and is independent of the AOP framework. Generally, AspectJ and Spring are used together to facilitate the operation of AOP. AspectJ is an aspect-oriented framework. It extends the Java language. Aspect defines the AOP grammar. The compiler is used to generate class files that comply with the Java bytecode specification. You can also understand AspectJ as a tool for implementing AOP operations.

   ②There are generally two ways to implement AOP operations based on AspectJ:

   <1> Implementation based on XML configuration

   <2>Based on annotation method (emphasis on mastering)

   Although most of the development is now implemented using annotation methods, the annotation method development is evolved from the XML method, and the annotation method is based on XML.

   ③Introduce jar package related dependencies in the project

   ④ Entry point expression

      <1>Function: Set which method in the class is to be enhanced. In layman's terms, it is to locate the points that need to be enhanced.

      <2>Syntax: execution([Permission Modifier][Return Type][Full Path of Class][Method Name]([Parameter List]))

      Example 1 : Enhance the add method in the com.it.dao.BookDao class.

      The permission modifier can be replaced by *. Classes and methods are connected by dots (.), and the parameters in the method are replaced by two dots (..)

      Implementation: execution (*com.it.dao.BookDao.add(..))

      Example 2: Enhance all methods in the com.it.dao.BookDao class.

      The permission modifier can be replaced by *. Classes and methods are connected by dots (.), all methods are replaced by *, and the parameters in the method are replaced by two dots (..)

      Implementation: execution (*com.it.dao.BookDao.*(..))

      Example 3: Enhance all classes and methods in com.it.dao

      The permission modifier can be replaced by *. Classes and methods are connected by dots (.), all methods are replaced by *, and the parameters in the method are replaced by two dots (..)

      Implementation: execution (*com.it.dao.*.*(..))

   ⑤Achieve operations in AspectJ through annotations

    First guide the package, and   download the specific package to   https://search.maven.org/

     (1) Create a User class to enhance the methods in the class. This class is the enhanced class

     (2) Create enhanced classes and write enhanced logic.

     Create methods in the enhanced class so that different methods represent different notification types.

     (3) To enable annotation scanning in the spring configuration file, you need to configure the context space

     

   (4) Use annotations to create User and UserProxy objects

   

<!-- 开启组件扫描 -->
<context:component-scan base-package="com.test.cn.aopannoation"></context:component-scan>

<!-- 开启AspectJ代理对象扫描 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

  (5) Add the annotation @Aspect above the enhanced class to indicate the proxy object of the generated class

@Aspect
public class UserDaoImpl implements UserDao{
    
}

  (6) Turn on the generation of proxy objects in the spring configuration file and use the aop space

    (7) Configure different types of notifications. In the enhanced class, add the annotations of the notification method above the notification method, and use the entry point expression to complete. It means to add a comment on the top of the notification, and after scanning it, you can confirm which is the comment of the enhanced class method

    Finish the method enhancement before the add() method, post-enhancement, surround-enhancement, and throw an exception if there is an exception.

Note: after is executed after the method is executed, afterReturning is executed when the method is executed to obtain the return value of the method. The parameters in the surround notification are the entry point (the method needs to be enhanced)

summary:

①Configure the scanning creation object of the spatial context in the xml file and the opening of aop to generate the proxy object

②Add the annotation @Component on the class and @Aspect on the enhanced class to generate proxy objects. The agent is responsible for notifying the methods of the original class, and specifying which method requires notification through the annotation pointcut expression.

③The method of the enhanced class is executed during the test

     (8) Extracting the same entry point, extracting methods that need to be enhanced

    (9) The same method is enhanced by multiple enhancement classes, and the priority of the enhancement classes can be set. Whoever executes it first, who executes it later.

      Add the annotation @Order (number type) to the enhanced class. The smaller the number type, the higher the priority.

     

     (10) Fully annotated development

See specifically:

https://www.cnblogs.com/coderxiaohei/p/11758239.html

@EnableAspectJAutoProxy(proxyTargetClass = true) is the CGLIB proxy used

@EnableAspectJAutoProxy(proxyTargetClass = false) is the jdk dynamic proxy used

to sum up:

The java dynamic proxy is to use the reflection mechanism to generate an anonymous class that implements the proxy interface, and call InvokeHandler to process it before calling the specific method.

The cglib dynamic proxy uses the asm open source package to load the class file of the proxy object class and process it by modifying its bytecode to generate subclasses.

1. If the target object implements the interface, the dynamic proxy of the JDK will be used to implement AOP by default 

2. If the target object implements the interface, you can force the use of CGLIB to implement AOP 

3. If the target object does not implement the interface, the CGLIB library must be used, and spring will automatically switch between the JDK dynamic proxy and CGLIB

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin blog.csdn.net/Sunshineoe/article/details/112591386