AOP application and code implementation (detailed analysis)

Posted by persia on Sun, 20 Feb 2022 11:15:14 +0100

catalogue

1. Introduction

1.1 main processes / functions of IOC

1.2 concept diagram of AOP

1.3 AOP flow chart

2. Basic preparations

------------------------------The configuration file implements AOP----------------------------

3. Introduction to AOP configuration file mode

4. Expression of pointcut (the * sign is not recommended)

-----------------------------Implement AOP by annotation----------------------------

5. Introduction procedure of AOP annotation method

5.1 # configure xml scanning annotation

5.2 configuration notes

5.3 add annotation @ Aspect to the Aspect class, write enhanced methods, and use notification type annotation declaration

5.4 testing

1. Introduction

1.1 main processes / functions of IOC

1.2 concept diagram of AOP

1.3 AOP flow chart

Suppose a class Demo

--------------------------AOP related terms------------------------------

  • What methods can be enhanced in the joinpoint class? These methods are called join points
  • Pointcut - the so-called pointcut refers to the definition of which joinpoints we want to intercept and the actual method to enhance.
  • Advice - the so-called notification refers to the notification of what needs to be done after intercepting the Joinpoint Notification is divided into pre notification, post notification, exception notification, final notification and surround notification (functions to be completed in all aspects). The logical part of the actual enhancement is notification
    • The pre notification is enhanced before the target method is executed

    • After the post notification target method is successfully executed, it is enhanced.

    • The surround notification target method can be enhanced before and after execution. The method of the target object needs to be executed manually.

    • After the execution of the exception notification target method fails, enhance it. (it will be executed only when an exception occurs, otherwise it will not be executed). Once the method is abnormal, it will be notified.

    • Finally, the target method will be notified of success or failure and enhanced. Similar to finally

  • Aspect -- it is a combination of pointcut and notification. We will write and configure it ourselves in the future. A process by which notifications are applied to pointcuts

2. Basic preparations

AspectJ is an oriented section Framework, which extends the Java language. AspectJ defines AOP syntax. AspectJ is actually a practice of AOP programming ideas

------------------------------The configuration file implements AOP----------------------------

3. Introduction to AOP configuration file mode

3.1 create maven project, coordinate dependency

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.0.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <version>1.2</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>5.0.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.12</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
    <!--AOP union-->
    <dependency>
        <groupId>aopalliance</groupId>
        <artifactId>aopalliance</artifactId>
        <version>1.0</version>
    </dependency>
    <!--Spring Aspects-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>5.0.2.RELEASE</version>
    </dependency>
    <!--aspectj-->
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.8.3</version>
    </dependency>
</dependencies>

3.2 create an enhanced user class java

package com.qcby;

import org.springframework.stereotype.Component;

public class User {
   public void add(){
//        int a= 10/0;
        System.out.println("add method");
    }
}

3.3 # define the section class userporxy java

package com.qcby;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;


public class UserPorxy {
//    Enhancement / notification -- pre notification
    public void before(){
        System.out.println("Section class before Execute first");
    }

//    public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
//        System.out.println("this is around before the add method is executed.);
//
//        //Perform enhanced methods
//        proceedingJoinPoint.proceed();
//
//        System.out.println("this is executed after the add method is executed (around));
//    }
    // Whether the pointcut succeeds or fails, the process will execute, similar to finally

//    public void after(){
//        System.out.println("this is executed after the add method is executed.);
//    }
    // Post notification: like after, it is executed after the method is executed, but after will execute the process regardless of the success or failure of the pointcut

//    public void afterReturning(){
//        System.out.println("afterReturning");
//    }

//    public void afterThrowing(){
//        System.out.println("afterThrowing....");
//    }


}

3.4 configure the target class into springconfig xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">


<bean id="user" class="com.qcby.User"/>
<bean id="userPorxy" class="com.qcby.UserPorxy"/>


<!--Configuration section-->
<aop:config>
    <!--Configuration section = breakthrough point + Notification composition-->
    <aop:aspect ref="userProxy">
        <!--Advance notice: UserServiceImpl of save Before the method is executed, it will be enhanced-->
        <!--pointcut: The following is the pointcut expression, which is used to enhance the opposite method-->
        <aop:before method="before" pointcut="execution(public void com.aopImpl.User.add())"/>
               <!--Around Advice -->
<!--                <aop:around method="around" pointcut="execution(public void com.qcby.User.add())"/>-->
                <!--Final notice-->
<!--                <aop:after method="after" pointcut="execution(public void com.qcby.User.add())"/>-->
                <!--Post notification-->
<!--                <aop:after-returning method="afterReturning" pointcut="execution(public void com.qcby.User.add())"/>-->
                <!--Exception notification-->
<!--                <aop:after-throwing method="afterThrowing" pointcut="execution(public void com.qcby.User.add())"/>
         
    </aop:aspect>
</aop:config>


</beans>

3.4 complete demotest java

package com.qcby.test;

import com.qcby.User;
import javafx.application.Application;
import jdk.nashorn.internal.ir.CallNode;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class DemoTest {
    @Test
    public void aopTest(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("SpringConfig.xml");
        User user = (User) ac.getBean("user");
        user.add();
    }

}

The five types should be tested separately, with one comment after the test

4. Expression of pointcut (the * sign is not recommended)

When reconfiguring pointcuts, you need to define expressions, which are expanded as follows:

The format of the pointcut expression is as follows:

execution([modifier] [return value type] [class full path] [method name ([parameter]))

Modifiers can be omitted and are not required.

The return value type cannot be omitted. Write the return value according to your method. You can use * instead.

-----------------------------Implement AOP by annotation----------------------------

5. Introduction procedure of AOP annotation method

Create maven project and import coordinates. Write the interface to complete the operation of IOC. The steps are omitted.

Write facet class

Add annotation @ Aspect to the Aspect class, write enhanced methods, and annotate the declaration with notification type

5.1 # configure xml scanning annotation

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--Enable annotation scanning-->
   <context:component-scan base-package="com.qcby"/>
    <!--open Aspect Generate proxy object-->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
    
</beans>

5.2 configuration notes

package com.qcby;

import org.springframework.stereotype.Component;

@Component
public class User {

    public void add(){
//        int a= 10/0;
        System.out.println("add method");
    }

}

5.3 add annotation @ Aspect to the Aspect class, write enhanced methods, and use notification type annotation declaration

package com.qcby;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class UserPorxy {
//    Enhancement / notification -- pre notification
    @Before(value = "execution(public void com.qcby.User.add())")
    public void before(){
        System.out.println("Section class before Execute first");
    }

//@Around(value = "execution(public void com.qcby.User.add())")
//    public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
//        System.out.println("this is around before the add method is executed.);
//
//        //Perform enhanced methods
//        proceedingJoinPoint.proceed();
//
//        System.out.println("this is executed after the add method is executed (around));
//    }
    // Whether the pointcut succeeds or fails, the process will execute, similar to finally

//    @After(value = "execution(public void com.qcby.User.add())")
//    public void after(){
//        System.out.println("this is executed after the add method is executed.);
//    }
    // Post notification: like after, it is executed after the method is executed, but after will execute the process regardless of the success or failure of the pointcut

//    @AfterReturning(value = "execution(public void com.qcby.User.add())")
//    public void afterReturning(){
//        System.out.println("afterReturning");
//    }

//   @AfterThrowing(value = "execution(public void com.qcby.User.add())")
//    public void afterThrowing(){
//        System.out.println("afterThrowing....");
//    }


}

5.4 testing

package com.qcby.test;

import com.qcby.User;
import javafx.application.Application;
import jdk.nashorn.internal.ir.CallNode;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class DemoTest {
    @Test
    public void aopTest(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("SpringConfig.xml");
        User user = (User) ac.getBean("user");
        user.add();
    }

}

5.5 result presentation (five separate tests. When testing exceptions, you need to write a divide by 0 exception in User.java)

 

Topics: Java Spring AOP