首页 > 解决方案 > Spring AOP 没有错误但不执行通知

问题描述

我是 Spring AOP 的新手,并通过以下baeldung文章尝试了以下代码。

方面类:

@Aspect
@Component
public class LoggingAspect {

    private final static Logger LOGGER = LoggerFactory.getLogger(LoggingAspect.class);

    @Around("@annotation(Debug)")
    public Object beforeDebug(ProceedingJoinPoint debugJoinpoint) {
        LOGGER.debug("----------------Debug message logged from {}", debugJoinpoint.getSignature().toString());
        System.out.println("IN HERE");
        long start = System.currentTimeMillis();

        Object proceed = null;
        try {
            proceed = debugJoinpoint.proceed();
        } catch (Throwable e) {
            e.printStackTrace();
        }

        long executionTime = System.currentTimeMillis() - start;

        System.out.println(debugJoinpoint.getSignature() + " executed in " + executionTime + "ms");
        return proceed;
    }
}

注解:

@Retention(RUNTIME)
@Target(METHOD)
@Loggable(type = "debug")
public @interface Debug {
}

用于测试的演示类:

@SpringBootApplication
@Component
public class Application {

    public static void main(String[] args) throws InterruptedException {
        SpringApplication.run(Application.class, args);
        dumb();
    }

    @Debug
    public static void dumb() throws InterruptedException {
        Thread.sleep(2000);
    }
}

有人可以指出我在上面做错了什么吗?该建议不会执行,并且在到处搜索之后我无法解决这个问题,不确定我错过了什么。

标签: javaspringspring-bootspring-aop

解决方案


Spring AOP 仅适用于非静态方法,如 Baeldung 示例中所示并记录在 Spring 手册中。


推荐阅读