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

标注Aspect与注解接口后AspectJ日志未触发的原因排查

Spring AOP环绕日志未触发的问题修复

你的代码逻辑本身没问题,但日志没触发是因为两个核心问题:

问题1:静态方法testing_a_run()无法被Spring AOP拦截

  • 这个方法是静态方法,Spring AOP默认只支持代理Bean的非静态实例方法,静态方法不在代理范围内;
  • 而且你在SpringApplication.run()之前就调用了它,此时Spring容器还没初始化,切面逻辑根本没加载,自然不会生效。

问题2:Service的serve()方法从未被调用

虽然你给serve()加了@LogExecutionTime注解,但整个应用启动后,没有任何地方调用这个方法,切面当然不会触发日志。


修正后的代码示例

启动类修改(实现CommandLineRunner,确保容器启动后调用方法)

@SpringBootApplication
@EnableAspectJAutoProxy
public class Demo1Application implements CommandLineRunner {
    private static final Logger logger = LoggerFactory.getLogger(Demo1Application.class);
    private final Service service;

    // 构造注入Service Bean
    public Demo1Application(Service service) {
        this.service = service;
    }

    public static void main(String[] args) {
        SpringApplication.run(Demo1Application.class, args);
    }

    @LogExecutionTime
    void testingARun() {
        logger.info("Handling hello request");
    }

    @Override
    public void run(String... args) throws Exception {
        // 容器启动完成后调用目标方法
        testingARun();
        service.serve();
    }
}

其他代码保持不变(Service、切面、自定义注解无需修改)


修正后预期的控制台输出

你会看到类似这样的日志(包含Before、After和环绕计时日志):

Method execution started: void com.example.demo.Demo1Application.testingARun()
Handling hello request
Method execution completed: void com.example.demo.Demo1Application.testingARun()
void com.example.demo.Demo1Application.testingARun() executed in Xms
Method execution started: void com.example.demo.Service.serve()
Method execution completed: void com.example.demo.Service.serve()
void com.example.demo.Service.serve() executed in 2000ms

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 11:53:17