springboot注解式AOP通过JoinPoint获取参数 学习笔记

springboot注解式AOP通过JoinPoint获取参数 学习笔记

之前开发时,需要获取切点注解的参数值,记录一下

切面注解 :
@Aspect – 标识为一个切面供容器读取,作用于类
@Pointcut – (切入点):就是带有通知的连接点
@Before – 前置
@AfterThrowing – 异常抛出
@After – 后置
@AfterReturning – 后置增强,执行顺序在@After之后
@Around – 环绕

1.相关maven包

	<dependency>
	    <groupId>org.springframework.bootgroupId>
	    <artifactId>spring-boot-starter-aopartifactId>
	dependency>

2.自定义一个注解

import java.lang.annotation.*;

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Action {
    String value() default "list";
}

3.定义切面类

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Aspect
@Component
public class ActAspect {
	
	@AfterReturning("@annotation(包名.Action)")
    public void afterReturning(JoinPoint point){
    
		// 获取切入点方法名
		String methodName = point.getSignature().getName();
		
    	// 获取注解中的参数值
        MethodSignature methodSignature = (MethodSignature)point.getSignature();
        Method method = methodSignature.getMethod();
        // 获取注解Action 
        Action annotation = method.getAnnotation(Action.class);
        // 获取注解Action的value参数的值
        String value = annotation.value();
        
        // 获取切点方法入参列表
        Object[] objArray = point.getArgs();
        // 下面代码根据具体入参类型进行修改
        List<String> list = new ArrayList<>();
        for (Object obj: objArray) {
            if(obj instanceof Collection){
                list = (List<String>) obj;
            }
        }
    }
    
}

参考博客:

https://blog.csdn.net/zhanglf02/article/details/78132304
https://www.tpyyes.com/a/javaweb/181.html
https://blog.csdn.net/qq_35098526/article/details/88397657

你可能感兴趣的:(Spring,aop,spring)