You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何@AfterReturning PointCut无法生效?Spring AOP切面问题

问题分析与解决方案

核心问题1:通知方法参数类型不匹配

ShoppingCart.quantity()返回的是int类型,但你的@AfterReturning通知方法参数定义为String retVal,类型不匹配会导致Spring AOP跳过该通知的执行。

核心问题2:缺少AOP自动代理配置

你的Main类中使用了BeanConfig,但如果该配置类没有开启AspectJ自动代理,Spring无法识别切面并生成代理对象,切面逻辑自然不会生效。


修改步骤

1. 修正通知方法的参数类型

修改AuthenticationAspect.java中的afterReturning方法,将参数类型改为int(或Integer,支持自动装箱):

package org.example;

import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class AuthenticationAspect {

    @Pointcut("execution(* org.example.ShoppingCart.quantity())")
    public void afterReturningPointCut() {}

    @AfterReturning(pointcut = "afterReturningPointCut()", returning = "retVal")
    public void afterReturning(int retVal) {
        System.out.println("The quantity used is " + retVal);
    }
}

2. 完善BeanConfig配置类

确保BeanConfig.java开启AspectJ自动代理并扫描组件:

package org.example;

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

@Configuration
@ComponentScan("org.example")
@EnableAspectJAutoProxy
public class BeanConfig {
}

验证效果

运行Main类后,控制台会输出:

Quantity method called
The quantity used is 2

内容的提问来源于stack exchange,提问作者TestUser

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 21:25:18