Spring - AOP - Basic Use

Series Length

Preface

This article will sort out AOP related knowledge, not directly introduce the theory here, let's see how to use it in our daily work

Relationship among Filter, Interceptor, ControllerAdvice, AOP

Process description

  1. Join dependent spring-aspects
  2. Add both business logic components and facet classes to the container and facet classes to the annotation @Aspect
  3. Label a notification annotation on each notification method on the facet class to tell Spring when and where to run the entry point expression
  4. Turn on annotation-based aop mode@EnableAspectJAutoProxy
Notification Method Explain
Pre-notification (@Before) Run before the target method runs
Post Notification (@After) Run after normal/abnormal end of target method
Return notification (@AfterReturning) Run after the target method returns normally
Exception notification (@AfterThrowing) Run after the target method has an exception
Wrap Notification (@Around) Dynamic proxy to manually push the target method to run joinPoint.procced()

Introducing dependencies

Lombok recommends: [Use of Lombok] (.../.../Java/programming skills/use of Lombok.md)

<!-- lombok Personal habits are not necessary -->
<dependency>
  <groupId>org.projectlombok</groupId>
  <artifactId>lombok</artifactId>
  <version>1.18.10</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
  <version>4.3.12.RELEASE</version>
</dependency>
<!-- aop Faces must be imported -->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-aspects</artifactId>
  <version>4.3.12.RELEASE</version>
</dependency>

Description of Common Methods

JoinPoint parameter must be first

Called before a class method executes

@After("execution(public int com.xm.demo.MathCalculator.*(..))")
public void logEnd(JoinPoint joinPoint){
  String methodName = joinPoint.getSignature().getName();
  System.out.printf("Method:%s End, Face Class: logEnd Method", methodName);
}

Pull out the common expression of the cut surface for easy reading and encapsulation

@Pointcut("execution(public int com.xm.demo.MathCalculator.*(..))")
public void pointCut() {
}

/**
 * Common cut-in expressions for this class
 */
@Before("pointCut()")
public void logStart(JoinPoint joinPoint) {
  Object[] args = joinPoint.getArgs();
  String methodName = joinPoint.getSignature().getName();
  System.out.printf("Method:%s About to run, parameter list:%s,Face class: logStart Method", 
                    methodName, Arrays.asList(args));
}

/**
 * Common cut-in expressions for other classes
 */
@After("com.xm.demo.LogAspects.pointCut()")
public void logEnd(JoinPoint joinPoint) {
  String methodName = joinPoint.getSignature().getName();
  System.out.printf("Method:%s End, Face Class: logEnd Method", methodName);
}

Complete example

Define function class, wait for slice log

public class MathCalculator {
    public int div(int i, int j) {
        System.out.printf("Method: MathCalculator.div(%d,%d)\n", i, j);
        return i / j;
    }
}

Define Face Class @Aspect must be added or invalid

@Aspect
public class LogAspects {

  /**
   * Extracting common entry point expressions
   */
  @Pointcut("execution(public int com.xm.demo.MathCalculator.*(..))")
  public void pointCut() {
  }


  @Before("pointCut()")
  public void logStart(JoinPoint joinPoint) {
    Object[] args = joinPoint.getArgs();
    String methodName = joinPoint.getSignature().getName();
    System.out.printf("Method:%s About to run, parameter list:%s,Face class: logStart Method\n",
                      methodName, Arrays.asList(args));
  }

  @After("com.xm.demo.LogAspects.pointCut()")
  public void logEnd(JoinPoint joinPoint) {
    String methodName = joinPoint.getSignature().getName();
    System.out.printf("Method:%s End, Face Class: logEnd Method\n", methodName);
  }

  @AfterReturning(value = "pointCut()", returning = "result")
  public void logReturn(JoinPoint joinPoint, Object result) {
    String methodName = joinPoint.getSignature().getName();
    System.out.printf("Method:%s Normal return,Return results:%s,Face class: logReturn Method\n",
                      methodName, result);
  }

  @AfterThrowing(value = "pointCut()", throwing = "exception")
  public void logException(JoinPoint joinPoint, Exception exception) {
    String methodName = joinPoint.getSignature().getName();
    System.out.printf("Method:%s abnormal,exception: %s,Face class: logException Method\n",
                      methodName, exception);
  }

}

Configuration class @EnableAspectJAutoProxy must be added or invalid

@EnableAspectJAutoProxy
@Configuration
public class MainConfig {

    /**
     * Business logic classes are added to containers
     */
    @Bean
    public MathCalculator mathCalculator(){
        return new MathCalculator();
    }

    /**
     * Cutting class added to container
     */
    @Bean
    public LogAspects logAspects(){
        return new LogAspects();
    }

}

Use

public class MainTest {
  public static void main(String[] args) {
    AnnotationConfigApplicationContext context =
      new AnnotationConfigApplicationContext(MainConfig.class);
    // Cutting is invalid if the ioc container is not practical
    MathCalculator calculator = context.getBean(MathCalculator.class);
    int div = calculator.div(4, 2);
    System.out.printf("result: %d", div);
  }
}

Normal results

Method: div is about to run, parameter list: [4, 2], tangent class: logStart method
 Method: MathCalculator.div(4,2)
Method: div end, tangent class: logEnd method
 Method: div returns normally, result: 2, tangent class: logReturn method
result: 2

Failure Result

Method: div is about to run, parameter list: [1, 0], tangent class: logStart method
 Method: MathCalculator.div(1,0)
Method: div end, tangent class: logEnd method
 Method: div exception, exception: java.lang.ArithmeticException: / by zero, tangent class: logException method
182 original articles published. 33% praised. 250,000 visits+
Private letter follow

Keywords: Spring Lombok Java calculator

Added by litebearer on Sun, 26 Jan 2020 04:57:06 +0200