Spring的AOP切指定的注解

本文介绍了一种使用AOP(面向切面编程)进行接口日志记录的方法。通过定义@InterfaceLog注解和@Aspect切面,实现了对带有指定注解方法的日志记录功能。文章展示了如何在Spring框架中配置并应用这一机制。

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

@Aspect//作用是把当前类标识为一个切面供容器读取
@Component
public class InterfaceLogAspect {
	//全路径是怕有重名的注解
    @Around("@annotation(路径.InterfaceLog)")
    public Object log(ProceedingJoinPoint pjp) throws Exception {
        // 從切點上獲取目標方法
        Method method = ((MethodSignature)pjp.getSignature()).getMethod();
        //拿到注解
        InterfaceLog interfaceLog = method.getAnnotation(InterfaceLog.class);
        Object response = null;
        long startTime = System.currentTimeMillis();
        try {
            // 目标方法执行
            response = pjp.proceed();

        } catch (Throwable throwable) {
            throw new Exception(throwable);
        }
        long elapsedTime = System.currentTimeMillis()-startTime;
        if (!StringUtils.isEmpty(interfaceLog.reqParamsName())) {

            Map<String, Object> context = new HashMap<>();
            // 获取参数值  返回执行目标方法时的参数值
            Object[] args = pjp.getArgs();

            // 获取运行时参数的名称
            LocalVariableTableParameterNameDiscoverer discoverer = new LocalVariableTableParameterNameDiscoverer();
            String[] parameterNames = discoverer.getParameterNames(method);
            }

注解

@Retention(RUNTIME)
public @interface InterfaceLog {}

启动类
@EnableAspectJAutoProxy
表示开启AOP代理自动配置,
开启注解支持

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值