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

Spring AOP切面方法未触发,求问题排查与修复方案

问题分析与修复方案

你的自定义Aspect未生效主要有三个核心问题:

1. 切面类未被Spring容器管理

MyAspect仅添加了@Aspect注解,但没有被Spring扫描并纳入容器,Spring无法识别这是一个需要生效的切面组件。

2. @Before切点表达式语法错误

@Before("@annotation(annotations.MyAnnotation)*")末尾多了一个多余的*,导致表达式解析失败,无法匹配到目标方法。

3. Controller方法访问权限错误

MyRestController中的callMyMethod是private修饰,Spring MVC无法识别并映射该请求方法,会导致你调用接口时无法触发目标方法(虽不是Aspect不生效的直接原因,但会影响验证效果)


修复步骤

修复MyAspect.java

添加@Component注解让Spring管理切面,同时修正切点表达式:

package annotations;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class MyAspect {

    @Before("@annotation(annotations.MyAnnotation)")
    public void interceptMethods(final JoinPoint thisJoinPoint) {
        System.out.println("Aspect触发:" + thisJoinPoint);
    }
}

修复MyRestController.java

将callMyMethod改为public:

package annotations;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyRestController {

    @Autowired
    MyClass myClass;

    @GetMapping("/myClass")
    public int callMyMethod() {
        return myClass.myMethod(1);
    }
}

验证效果

启动应用后访问http://localhost:8080/myClass,控制台会先输出Aspect触发:execution(int annotations.MyClass.myMethod(int)),再输出method: 1,说明Aspect已正常生效。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 17:20:59