Call of aspect oriented programming in Spring

Posted by adksga on Thu, 06 Jan 2022 06:07:51 +0100

Knowledge point set about AOP

Concept: AOP is the abbreviation of Aspect Oriented Programming, which means Aspect Oriented Programming

Aspect oriented programming: define and encapsulate the extended method in the aspect. There is no need to modify the source code to extend the method, and there may be many aspects

Function: it can isolate each part of business logic, reduce the coupling degree between each part of business logic, improve program reusability and improve development efficiency.

Summary: AOP in Spring uses proxy objects to extend methods without modifying the source code

Terminology in AOP

1. Connection point: a method by which users can be extended

2. Pointcut: the method actually extended by the user (the notification method will be executed when the method meets the pointcut expression)

3. Notice: specific implementation of extension method

4. Aspect: the process of applying notifications to pointcuts

Pointcut expression:

bean("object id") intercepts only one at a time

@Pointcut("bean(userServiceImpl)") only matches userServiceImpl with ID

within("package name. Class name")

@Pointcut("within(com.jt.demo2.userservice.*)")
        Match XX xxx. All paths under userservice
    Note: for the above operations, the granularity is coarse. Match by class

execution("return value type package name. Class name. Method name (parameter list)") method parameter level

@Pointcut ("execution (* com. JT. Demo2. Userservice (package name).. *. * (..)")
** intercept the return value of any type XX xx. Any method of all classes of all descendant packages under userservice package
java has a variable parameter type
*        @Pointcut("execution(* com.jt.demo2.userservice..*.add*(..)
*Intercept return value of any type XX xx. All classes of all descendant classes under the service package Methods starting with add

@Annotation (path of annotation)

@Pointcut("@annotation(com.jt.demo2.anno.CGB2110)")
*Intercept the annotation of CGB2110 under XX package

Define notification method:


     *   1. The pre - notification is executed before the target method is executed

@Before("pointcut1()")
public  void before(JoinPoint joinPoint){
    System.out.println("this method is pre notification");
}

     *   2. The post notification is executed after the target method is executed

@AfterReturning("pointcut2()")
public  void afterReturning(){
    System.out.println("this method is a post notification");

     *   3. Exception notification is executed when an exception is thrown after the target method is executed

@AfterThrowing("pointcut3()")
public  void afterThrowing(){
    System.out.println("this method is exception notification");

     *   4. The final notice is the notice to be executed

@After("pointcut4()")
public  void After(){
    System.out.println("this method is the final notice");
}

The above is the running status of the recording program

     *   5. Surround Notification - notification to be executed before and after the execution of the target method - controls whether the target method is executed

@Around("")
public  void Around(){
    System.out.println("this method is a surround notification");
}

Execution sequence in spring AOP:


 

AOP writing process:

preparation:

Step 1: create com jt. aop1

Step 2: create three layers under aop1 package: AOP, config and service

Step 3: create SpringAop under aop, which is an aspect class

Create SpringConfig under config

Create an interface UserService implementation class UserserviceImpl under service

Create a test class at the same level as the three packages

Code layered display

 SpringAop

@Component//Leave the current class to the spring container
@Aspect//Indicates that it is currently a faceted class
public class SpringAop {

SpringConfig

package com.jt.aop1.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@Configuration
@ComponentScan("com.jt.aop1")
//Make AOP in Spring work
@EnableAspectJAutoProxy
public class SpringConfig {


}

UserService

package com.jt.aop1.service;

public interface UserService {
    void addUser();
    void deleteUser();
}

UserserviceImpl

package com.jt.aop1.service;

import com.jt.aop1.note.ZHUJIE1;
import com.jt.aop1.note.ZHUJIE2;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;


@Service//Indicate business layer
public class UserServiceImpl implements UserService {
    @Override
   
    public void addUser(){
        System.out.println("In the business layer addUser New user");
    }
    @Order
    
    public void deleteUser(){
        System.out.println("In the business layer delete delete user");
    }
}

Test method:

package com.jt.aop1;

import com.jt.aop1.config.SpringConfig;
import com.jt.aop1.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Spring_AOP {
    /**
     * technological process:
     * 1.First go to the first two lines, scan the configuration class inside, scan the first two annotations of the configuration class, and the AOP will take effect
     * 2.SpringAop After it takes effect, the scan annotation @ Aspect will consider the current class as a faceted class
     * 3.It will perform a series of operations in spring AOP
     * */
    public static void main(String[] args) {
        ApplicationContext context=
                new AnnotationConfigApplicationContext(SpringConfig.class);
//        Theoretically, the object of the implementation class is obtained according to the interface, but the proxy object is obtained by matching with the pointcut expression
//        Because the current class matches the expression in aop when it is obtained, a proxy object is created
//        Proxy object creation method: JDK dynamic proxy, CGLib dynamic proxy

        UserService userService = context.getBean(UserService.class);
//        Methods that implement class objects are not extended
//        The proxy object method will be extended to Aop
        System.out.println(userService.getClass());
//        Call business layer methods
        userService.addUser();
        userService.deleteUser();
        userService.updateUser();
        userService.saveUser();
    }
}

Start running process:

Start with the test class:

technological process:
* 1. First go to the first two lines of the test class, scan the configuration class inside, scan the first two annotations of the configuration class, and the AOP takes effect
 * 2. After spring AOP takes effect, scanning the annotation @ Aspect will consider the current class as an Aspect class
 * 3. It will perform a series of operations in spring AOP
Aspect = pointcut expression + notification method
*
* 1. Define a facet class
 * 2. Create a method -- expression + notification method
 *(you need to set an annotation for this public method and replace it with the method name,
*The path inside is set as the bean pointcut expression, and the method in the class of the business layer is called in the tag)
*The test class starts scanning. After completing the process of the test class, start to execute 3
 * 3. To make spring AOP effective, add the annotation @ EnableAspectJAutoProxy in the configuration class
 * 4. Start scanning @ Pointcut to determine whether the current object userServiceImpl is running in the bean tag
 * 5. If it is satisfied, the section expression will be executed, and the following notification methods bound to the pointcut expression will be executed. Because it is the front, it will be executed with the target method first, and then obtain the implementation class object according to the interface,

Summary of loading process:

Specific loading steps of spring AOP: the way of configuration file
1. When the spring container is started, the spring configuration file is loaded
2. Create objects for all bean s in the configuration file
3. When the spring container creates an object, it will parse the configuration of aop:config
Parse the pointcut expression and match it with the bean included in the spring container
If the matching is successful, a proxy object will be created for the bean. The method of the proxy object = target method + notification
If the match is not successful, a normal object is created for the bean
In fact, you tell Spring which bean s need it to generate proxy objects instead of the original normal objects through expressions
   
4. Use context on the client When getBean gets an object, if the object has a proxy object, it returns the proxy object. If there is no proxy object, it returns the target object
 
Note: if the target class implements the interface, the spring container will use the dynamic proxy of jdk to generate the proxy object, and the generated proxy class and the target class implement the same interface;
If the target class does not implement the interface, the spring container will use cglib to generate proxy objects, and the generated proxy class is a subclass of the target class

Step 4: code function implementation

Build a module

package com.jt.aop1.aop;

@Component//Leave the current class to the spring container
@Aspect//Indicates that it is currently a faceted class
public class SpringAop {



}

1. Implement the bean pointcut expression + pre notification method in the aspect class code

package com.jt.aop1.aop;

@Component//Leave the current class to the spring container
@Aspect//Indicates that it is currently a faceted class
public class SpringAop {
 @Pointcut("bean(userServiceImpl)")
    public void pointcut1() {
    }
  @Before("pointcut1()")
    public void before() {
        System.out.println("This method is pre notification");
   }

Achieve presentation:

 2. Implement the pointcut expression of within + pre notification method in the aspect class code

package com.jt.aop1.aop;

@Component//Leave the current class to the spring container
@Aspect//Indicates that it is currently a faceted class
public class SpringAop {
//     2. Method of creating a within pointcut expression
    @Pointcut("within(com.jt.aop1.service.*)")
    public void pointcut2(){  }

 @AfterReturning("pointcut2()")
    public  void afterReturning(){
        System.out.println("This method is post notification");
    }
}

Achieve presentation:

3. Implement the pointcut expression of execution + exception notification method in the aspect class code

package com.jt.aop1.aop;

@Component//Leave the current class to the spring container
@Aspect//Indicates that it is currently a faceted class
public class SpringAop {

//    3. Method of creating an execution pointcut expression
    @Pointcut("execution(* com.jt.aop1.service..*.*(..))")
    public void pointcut3(){  }

    @AfterThrowing(value = "pointcut3()",throwing = "exception")
    public  void afterThrowing(Exception exception){
        System.out.println("This method is exception notification");
    }

}

 

4. Implement the pointcut expression of @ annotation + the final notification method in the aspect class code

package com.jt.aop1.aop;

@Component//Leave the current class to the spring container
@Aspect//Indicates that it is currently a faceted class
public class SpringAop {

//4. Create a @ annotation pointcut expression
    @Pointcut("@annotation(com.jt.aop1.note.BAOCUN)")
    public void pointcut4(){  }

 @After("pointcut4()")
    public  void After(){
        System.out.println("This method is the final notification");
    }

}

Business layer code:

package com.jt.aop1.service;

import com.jt.aop1.note.*;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;


@Service//Indicate business layer
public class UserServiceImpl implements UserService {
    @Override
    @TIANJIA
    public void addUser(){
        System.out.println("In the business layer addUser New user");
    }
    @Order
    @SHANCHU
    public void deleteUser(){
        System.out.println("In the business layer delete delete user");
    }

    @Override
    @XIUGAI
    public void updateUser() {
        System.out.println("Modify user information");
    }

    @Override
    @BAOCUN
    public void saveUser() {
        System.out.println("Save user information");
    }
}

Note: annotations are used as tags, so they are not used as dynamic proxies, but directly locate classes in the business layer through annotations

5. Implement the pointcut expression of @ annotation + surround notification method in the aspect class code

@Order() / / annotation for sorting

Topics: Java Spring mvc