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

本文介绍了如何在Spring Boot项目中使用注解式AOP,通过`JoinPoint`对象获取自定义注解的参数值,包括切点方法名、注解值和参数处理。适合开发者理解和应用切面编程在实际项目中的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

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

1.相关maven包

	<dependency>
	    <groupId>org.springframework.boot</groupId>
	    <artifactId>spring-boot-starter-aop</artifactId>
	</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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值