Spring ResponseEntityExceptionHandler.handleException 的 AOP 建议

Spring AOP Advice for ResponseEntityExceptionHandler.handleException

我是 Spring AOP 的新手。我尝试为 ResponseEntityExceptionHandler.handleException 方法编写建议以记录异常信息。经过数小时的寻找解决方案后,我被卡住了。

这是我的 Apect 组件

@Log4j2
@Aspect
@Component
public class LogginAspect {

  @Pointcut(value = "execution(* org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler.handleException(..)) && args(ex, request)")
  public void callSpringExceptionHandler() {}

  @Before("callSpringExceptionHandler()")
  public void logBeforeError(JoinPoint joinPoint, Exception ex, WebRequest request) {
    log.error(ex.getMessage(), ex);
  }
}

我尝试了不同的切入点模式,但没有成功。 我的建议 logBeforeError 根本不会调用。请帮我解决我的问题

来自 Spring 文档:5.8. Proxying Mechanisms

If the target object to be proxied implements at least one interface, a JDK dynamic proxy is used. All of the interfaces implemented by the target type are proxied. If the target object does not implement any interfaces, a CGLIB proxy is created.

With CGLIB, final methods cannot be advised, as they cannot be overridden in runtime-generated subclasses.

ResponseEntityExceptionHandler is an abstract class which does not implement any interface and ResponseEntityExceptionHandler.handleException()是最后一个方法。简而言之 Spring AOP 将无法通知该方法执行。

尽管如此,您将能够使用 AspectJ 实现建议最终方法。请仔细阅读来自@kriegaex

的详细 [​​=14=]