How to use AOP in SpringBoot

1. What is AOP

AOP (Aspect oriented programming) is the complement and perfection of OOP (object oriented programming). OOP introduces the concepts of encapsulation, inheritance and polymorphism to build an object hierarchy to simulate a set of public behaviors. When we need to introduce public behavior for decentralized objects, OOP is powerless. In other words, OOP allows you to define a top-down relationship, but it's not appropriate to define a left to right relationship. For example, log function. Log code tends to be distributed horizontally across all object levels, regardless of the core functions of the objects it spreads. This is also true for other types of code, such as security, exception handling, and transparent persistence. This kind of irrelevant code is called cross cutting code. In OOP design, it leads to a lot of code repetition, which is not conducive to the reuse of each module. AOP technology, on the other hand, uses a technology called "crosscutting" to dissect the inside of the packed objects, encapsulate the common behaviors that affect multiple classes into a reusable module, and call it "Aspect", that is, Aspect. The so-called "Aspect" is simply to encapsulate the logic or responsibility that has nothing to do with the business but is jointly called by the business modules, so as to reduce the repeated code of the system, reduce the coupling degree between the modules, and facilitate the operability and maintainability in the future. AOP represents a horizontal relationship. If the "object" is a hollow cylinder, which encapsulates the properties and behaviors of the object, then the Aspect oriented programming method is like a blade, which splits the hollow cylinders to get the internal information. And the cut is the so-called "Aspect". Then it uses its ingenious hand to restore these cut sections without leaving any trace.

2. Basic concept of AOP

  • 1. Aspect: usually a class that defines pointcuts and notifications
  • 2. Jointpoint: an explicit point in the execution of a program, usually a method call
  • 3. Advice: the enhanced processing performed by AOP at a specific entry point includes before, after, after returning, after throwing, around
  • 4. Pointcut (pointcut): it is a connection point with notification, which is mainly embodied in writing pointcut expression in the program
  • 5. AOP proxy: an object created by the AOP framework. Proxy is the enhancement of the target object. AOP proxy in Spring can make JDK dynamic proxy or CGLIB proxy. The former is based on interface and the latter is based on subclass

Notification method:

  • Pre notification: run before we execute the target method (@ Before)
  • Post notification: after our target method runs, no matter if there is any exception (@ After)
  • Return notification: run after our target method returns a normal value (@ AfterReturning)
  • Exception notification: run after our target method has an exception (@ AfterThrowing)
  • Circular notification: dynamic agents need to manually execute joinpoint. Procced() (in fact, the execution of our target method is equivalent to pre notification before execution, and after execution is equivalent to our post notification (@ Around)

3. How to use

  • 1. New profile
package com.newcapec.swaggerdemo.configuration;

import com.newcapec.swaggerdemo.aspect.Calculator;
import com.newcapec.swaggerdemo.aspect.LogAspects;
import com.newcapec.swaggerdemo.aspect.Sout;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

/**
 * AOP Configuration class
 * By pensai
 * Creation time: 10:14, January 13, 2020
 */
@Configuration
@EnableAspectJAutoProxy
public class AOPConfig {
    @Bean
    public Calculator calculator(){
        return new Calculator();
    }

    @Bean
    public LogAspects logAspects(){
        return new LogAspects();
    }

    @Bean
    public Sout sout(){
        return new Sout();
    }

}
  • 2. Write objective method
package com.newcapec.swaggerdemo.aspect;

/**
 * Target method
 * By pensai
 * Creation time: 10:27, January 13, 2020
 */
public class Calculator {
    //Business logic method
    public int div(int i, int j){
        System.out.println("--------");
        return i/j;
    }
    // My method
    public void print(){
        System.out.println("Calculator My own methods in class");
    }
}
  • Write cut class
package com.newcapec.swaggerdemo.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

//Log facet class
@Aspect
public class LogAspects {
    // Define the method to cut in, you can use wildcard method to specify
    @Pointcut("execution(* com.newcapec.swaggerdemo.aspect.Sout.*(..))")
    public void pointCut(){}

    //@Before stands for cutting in before the target method executes, and specifies which method to cut in before
    @Before("pointCut()")
    public void logStart(){
        System.out.println("Division operation....The parameter list is:{}");
    }
    @After("pointCut()")
    public void logEnd(){
        System.out.println("Division termination......");
    }
    @AfterReturning("pointCut()")
    public void logReturn(){
        System.out.println("Division normal return......The result is:{}");
    }
    @AfterThrowing("pointCut()")
    public void logException(){
        System.out.println("Abnormal operation......The exception message is:{}");
    }
    @Around("pointCut()")
    public Object Around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
        System.out.println("@Arount:Before executing the target method...");
        Object obj = proceedingJoinPoint.proceed();//It's like starting a div a
        System.out.println("@Arount:After executing the target method...");
        return obj;
    }
}

4. Test class

public class Cap10Test {
	@Test
	public void test01(){
		AnnotationConfigApplicationContext app = new AnnotationConfigApplicationContext(Cap10MainConfig.class);	
		Calculator c = app.getBean(Calculator.class);
		int result = c.div(4, 3);
		System.out.println(result);
		app.close();
 
	}
}

5. Required dependence

<!--AOP Related dependence-->
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjrt</artifactId>
        <version>1.9.1</version>
    </dependency>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.8.8</version>
    </dependency>
Published 32 original articles, won praise 4, visited 6670
Private letter follow

Tags: calculator Programming Spring JDK

Posted on Fri, 17 Jan 2020 04:22:10 -0500 by zleviticus