Spring 5 core 2: AOP aspect oriented

1, What is AOP

For aspect oriented programming, AOP can isolate all parts of business logic, so as to reduce the coupling between all parts of business logic, improve the reusability of programs, and improve the efficiency of development
Generally speaking, it means adding new functions to the main functions without modifying the source code.

2, AOP underlying principles (using dynamic agents)

  /**
     *
     *  AOP Underlying principle 
     * @author Herz
     * @date 2021/4/9 17:49
     */
    
    public class JDKProxy {
        public static void main(String[] args) {
    
            Class[] interfaces = {UserDao.class};
    
            UserDao userdao = (UserDao) Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, new UserDaoProxy(new UserDaoImpl()));
    
            System.out.println(userdao.sum(1, 2));

            userdao.update("Zhang San");
        }
    }
@SuppressWarnings("all")
//Create proxy object code
class UserDaoProxy implements InvocationHandler{

    //Pass in the target object from the proxy object of the created target object
    private Object obj;
    //Pass through parametric construction
    public UserDaoProxy(Object obj){
        this.obj = obj;
    }

    /*
        Enhanced logic
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //Before method
        System.out.println("method"+ method.getName() +"Before execution...., "+"The parameters passed in are:"+ Arrays.toString(args));

        //Enhanced method execution
        Object res = method.invoke(obj, args);

        //After method
        System.out.println("method"+ method.getName() +"After execution");

        return res;
    }
}
public interface UserDao {
    
        public int sum(int a, int b);
    
        public String update(String name);
    
    }
/**
     *
     * Enhanced class
     *
     * @author Herz
     * @date 2021/4/9 17:48
     */
    public class UserDaoImpl implements UserDao {
        @Override
        public int sum(int a, int b) {
            System.out.println("sum()Method executes...");
            return a + b;
        }
    
        @Override
        public String update(String name) {
            System.out.println("update()Method executes....");
            return name;
        }
    }

1) If there is an interface, use JDK dynamic agent.

Create the proxy object of the interface implementation class and enhance the method of the class

2) If there is no interface, use CGLIB dynamic proxy

Create proxy objects for subclasses of the current class and enhance the methods of the class

3, AOP operational terminology

1) Connection point: all methods that can be enhanced are called connection points.
2) Entry point: the actual enhanced method becomes the entry point
3) Notification (enhancement): the actually added enhancement logic part is called notification (enhancement).
Notification (enhanced) types: pre notification, post notification, surround notification, exception notification and final notification
4) Aspect: the process of applying notifications to pointcuts

4, AOP operation

1) Spring frameworks generally implement AOP operations based on AspectJ

AspectJ is not a part of Spring, but an independent AOP framework. Generally, Spring and AspectJ framework are used together for AOP operation.

2) AOP operation based on AspectJ

(1) Implementation of configuration file based on xml
(2) Annotation based implementation

3) Pointcut expression:

Function: know which or which methods of which or which classes are enhanced.
Syntax structure: execution (full path of value type class returned by permission modifier. Method name (parameter list))

Example 1: for com tianfei. The add() method in userdao class is enhanced:
execution(* com.tianfei.UserDao.add(...))

Example 2: com tianfei. All methods in the userdao class are enhanced
execution(* com.tianfei.UserDao.*(...))

Example 3: com All methods in all classes in Tianfei package are enhanced
execution(* com.tianfei..(...))

5, AOP operations implement AOP operations based on AspectJ annotations

1. Create the enhanced class User and define the method in the class

 //Enhanced class
    @Component //Create this kind of object
    public class User {
    
        public void add() {
            int i = 10 / 0;
    
            System.out.println("add.................");
        }
    }

2. Create enhancement class 1:UserProxy and enhancement class 2: PersonProxy (write enhancement logic)

 /**
     *
     *
     * Enhancement class 1:
     *
     *
     * @author Herz
     * @date 2021/4/12 10:18
     */
    @SuppressWarnings("all")
    
    @Component  //Create this kind of object
    @Aspect    //Create proxy object
    @Order(3)
    public class UserProxy {
    
        //Extraction of the same pointcut
        @Pointcut(value = "execution(* com.tianfei.aopanno.User.add(..))")
        public void pointCommon(){
    
        }
    
    
        //Before advice 
        @Before(value = "pointCommon()")
        public void before(){
            System.out.println("before................");
        }
    
        //Post notification (return notification): do not execute after an exception occurs
        @AfterReturning(value = "execution(* com.tianfei.aopanno.User.add(..))")
        public void afetReturning(){
            System.out.println("afetReturning................");
        }
    
        //Final notice: it will be implemented at any time
        @After(value = "execution(* com.tianfei.aopanno.User.add(..))")
        public void after(){
            System.out.println("after................");
        }
    
        //Exception notification: executed only when an exception occurs in the enhanced method
        @AfterThrowing(value = "execution(* com.tianfei.aopanno.User.add(..))")
        public void afterThrowing(){
            System.out.println("afterThrowing................");
        }
    
    
        //Surround notification: when an exception occurs in the enhanced method, only the code before surround is executed
        @Around(value = "execution(* com.tianfei.aopanno.User.add(..))")
        public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
            System.out.println("Before surround................");
    
            //Perform enhanced methods
            proceedingJoinPoint.proceed();
    
            System.out.println("After surround................");
        }
    }
/**
 *
 * Enhancement class 2
 *
 *
 *
 * @author Herz
 * @date 2021/4/12 15:56
 */
@Component  //create object
@Aspect     //Create proxy object
@Order(1)   //The smaller the number, the higher the priority
public class PersonProxy {

    @Before(value = "execution(* com.tianfei.aopanno.User.add(..))")
    public void personBerfore(){
        System.out.println("Person...Before...........");
    }
}

3. Configure notifications

(1) In the Spring configuration file, turn on annotation scanning

<!--Open annotation scanning component-->
<context:component-scan base-package="com.tianfei.aopanno"></context:component-scan>

(2) Use annotations to create enhanced class User and enhanced class UserProxy objects

(3) Add the annotation @ Aspect on the enhanced class

(4) Turn on the generation proxy object in the spring configuration file

<!--open AspectJ Generate proxy object-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

Supplement: full annotation can also be used (steps 1 and 4 can be omitted)

Create a class as the configuration class:

 /**
     *
     * Full annotation mode
     *      Create a configuration class
     *
     * @author Herz
     * @date 2021/4/12 16:29
     */
    @Configuration   //As a configuration class
    @ComponentScan(value = {"com.tianfei.aopanno"})   //Turn on the scan assembly
    @EnableAspectJAutoProxy(proxyTargetClass = true)  //Turn on AspectJ to generate proxy objects
    public class UserConfig {
    }

Test:

public class testaop {
    //AspectJ implements AOP operation test based on annotation
    @Test
    public void testAnno(){
//        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        //Full annotation
        ApplicationContext context = new AnnotationConfigApplicationContext(UserConfig.class);

        User user = context.getBean("user", User.class);
        user.add();
    }
}

6, Implementation of aotaspecj operation based on XML

1. Create the enhanced class Book and define the method in the class

 /**
     *
     * Enhanced class
     *
     * @author Herz
     * @date 2021/4/12 16:11
     */
    public class Book {
    
        public void add(){
            System.out.println("Book.....add.......");
        }
    }

2. Create enhanced class BookProxy (write enhanced logic)

/**
 *
 * Enhancement class
 *
 * @author Herz
 * @date 2021/4/12 16:12
 */
public class BookProxy {

    public void before(){
        System.out.println("Book....before.......");
    }
}

3. Configure notifications

(1) Configure and create enhanced class Book and enhanced class BookProxy objects in the Spring configuration file
(2) Configure aop enhancements in the spring configuration file

<!--to configure aop enhance-->
    <aop:config>
        <!--breakthrough point-->
        <aop:pointcut id="p" expression="execution(* com.tianfei.aopxml.Book.add(..))"></aop:pointcut>
        <!--Configuration section-->
        <aop:aspect ref="bookProxy">
            <!--In specific methods-->
            <aop:before method="before" pointcut-ref="p"></aop:before>
        </aop:aspect>
    </aop:config>

Test:

public class testaop {

    //AspectJ implements AOP operation test based on xml configuration file
    @Test
    public void testXml(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean2.xml");

        Book book = context.getBean("book", Book.class);
        book.add();
    }
}

Keywords: Spring AOP

Added by sirup_segar on Fri, 18 Feb 2022 23:18:49 +0200