【问题标题】:Spring AOP using aspectj - How to log internal methods? How to include final method calls in your aspect class?Proper Exception handling in AOPSpring AOP 使用 aspectj - 如何记录内部方法?如何在方面类中包含最终方法调用?AOP 中的正确异常处理
【发布时间】:2026-02-15 05:35:01
【问题描述】:

我使用Spring AOP做日志服务,遇到3个问题:

  1. 内部方法日志记录: 参考代码:How to Log all the methods public method calls in AOP

  2. 要在代理中包含最终方法: 按照 pmd、checkstyle 和 findbugs 中提到的代码标准,我们不能更改方法的 final 关键字。我尝试了接口并连接到呼叫但不起作用。

  3. 处理异常,然后返回服务本身以获取实际响应

@RestController("/person")
public Person getpersonInfo() {
    try {
        // (...)
        getValidPerson();
        return response; // response including person info
    }
    catch (Exception ex) {
        return response; // response stating the exception condition
    }
}

请提供您的宝贵建议。

【问题讨论】:

标签: spring-boot spring-aop


【解决方案1】:
    1234563因此,要么配置 Spring 以公开代理对象并在调用代理方法之前手动获取对代理的引用,要么从 Spring AOP 切换到 AspectJ with load-time weaving
  1. 从技术上讲,代理会在运行时生成子类。但是最终类不能扩展,最终方法不能被覆盖。因此,您无法使用代理处理它们。同样,如果您认为需要此功能,请切换到完整的 AspectJ。

  2. 这可以在@Around 建议中完成,如下所示:

@Around("... your pointcut ...")
public Object myAdvice(final ProceedingJoinPoint thisJoinPoint) throws Throwable {
    System.out.println(thisJoinPoint);
    try {
        return thisJoinPoint.proceed();
    }
    catch (Exception e) {
        e.printStackTrace();
        return "some other object";
    }
}

【讨论】: