Basic AOP usage of spring

Keywords: Spring Maven Apache Junit

AOP: [dynamic agent]
	It refers to the programming method that dynamically cuts a piece of code into a specified method position to run during the program running
 1. Import aop module: Spring AOP: (spring aspects)
2. Create a business logic class (MathCalculator): print the log when the business logic is running (exception, return before and after the method is running)
3. Define a log aspects class: Methods in the aspects class need dynamic awareness MathCalculator.div Run to that step, and then execute;
	Notification method:
		Advance notification (@ Begore): logStart: run before the target method (div) runs
		Post notification (@ After): logEnd: run after the target method (div) runs
		Return notification (@ AfterReturning): logReturn: run after the target method (div) returns normally
		Exception notification (@ AfterThrowing): logException: run after an exception occurs in the target method (div)
		Around notification (@ Around): dynamic agent, manual agent, manual promotion of target method operation( joinPoint.procced())
4. When and where to run the target method of the tangent class (annotation)
5. Add the aspect class and business logic class (target method class) to the container;
6. spring must be told that it's a tangent class, just add an annotation @ Aspect to the tangent class
 7. Add @ EnableAspectJAutoProxy [enable annotation based aop mode] to the configuration class
	Many @ EnableXXX in spring;

Step 1: dependence on environment construction

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.yu</groupId>
  <artifactId>spring</artifactId>
  <version>0.0.1-SNAPSHOT</version>
   <properties>
        <!--You can spring See the latest version on the official website https://spring.io/projects/spring-framework#learn-->
        <!-- Use the latest spring5  2019year10month5day 21:21:39the latest version -->
        <spring.version>5.2.0.RELEASE</spring.version>
    </properties>
    
  <dependencies>
  		<dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-context</artifactId>
		    <version>5.0.16.RELEASE</version>
		</dependency>
        <!--spring Core package-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--spring web package-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- springMVC-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
            <scope>compile</scope>
        </dependency>

        <!--jstl for jsp page-->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        
        <dependency>
		    <groupId>junit</groupId>
		    <artifactId>junit</artifactId>
		    <version>4.12</version>
		    <scope>test</scope>
		</dependency>
		
		 <!-- <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>  -->
 
        <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjrt
        import org.aspectj.lang.annotation.Aspect
        be used for@Aspect
        -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.9.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver
        Aspect Dependency package for
        -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.1</version>
        </dependency>
    </dependencies>
  
</project>

Step 2: write a business logic class, MathCalculator

package com.condition;


public class MathCalculator {
	public MathCalculator(){}
	//Business logic of division
	public int div(int i,int j){
		System.out.println("Run the division method. div. . ");
		return i/j;
	}
}

Step 3: define a log facet class, LogAspects

package com.condition;

import java.util.Arrays;

import org.aopalliance.intercept.Joinpoint;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
//@Aspect tells the container that this is a tangent class
@Aspect
public class LogAspects {
	@Pointcut("execution(public int com.condition.MathCalculator.*(..))")
	public void pubv(){}
	@Before("pubv()")
	public void logStart(JoinPoint joinPoint){
		Object[] objects = joinPoint.getArgs();
		System.out.println("In target method.."+joinPoint.getSignature().getName()+"..Execute parameter table before execution:{"+Arrays.asList(objects)+"}");
	}
	
	@After("pubv()")
	public void logEnd(JoinPoint joinPoint){
		System.out.println("In target method.."+joinPoint.getSignature().getName()+"..Execute after execution logEnd()method");
	}
	
	@AfterReturning(value="pubv()",returning="object")
	public void logReturn(JoinPoint joinPoint,Object object){
		System.out.println("In target method.."+joinPoint.getSignature().getName()+"..Execute on return..{"+object+"}");
	}
	
	@AfterThrowing(value="pubv()",throwing="exception")
	public void logException(JoinPoint joinPoint,Exception exception){
		System.out.println("In target method.."+joinPoint.getSignature().getName()+"..Execute when an exception is thrown..{"+exception+"}");
	}
}


Step 4: add the aspect class and business logic class (target method class) to the container

package com.config;

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

import com.condition.LogAspects;
import com.condition.MathCalculator;

@Configuration    //Tell the container this is an annotation class
 
@EnableAspectJAutoProxy    //Tell the container to turn on aop annotation mode
public class MianConfig3 {
	
	@Bean
	public MathCalculator mathCalculator(){
		return new MathCalculator();
	}
	
	@Bean
	public LogAspects getLogAspects(){
		return new LogAspects();
	}
}

Step 5: Test

package com;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.condition.MathCalculator;
import com.config.MianConfig3;

public class DemoTest {
	 
	 public static void main(String[] args) {
			AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MianConfig3.class);
			MathCalculator mathCalculator = applicationContext.getBean(MathCalculator.class);
			mathCalculator.div(1, 1);
			//Close container
			applicationContext.close();
	}
	
}



Summary:
Three steps:
1. Add the business logic component and the Aspect class to the container; tell Spring that it is the Aspect class (@ Aspect)
2, Annotate each notification method on the aspect class with a notification annotation to tell Spring when and where to run (pointcut expression)
3. Enable annotation based aop mode; @ EnableAspectJAutoProxy

Posted by ataylor20 on Mon, 08 Jun 2020 19:00:16 -0700