@AfterReturning从ExceptionHandler不起作用

时间:2020-08-19 03:01:56

标签: spring-aop

我有一个GlobalExceptionHandler类,其中包含用@ExceptionHandler注释的多个方法。

@ExceptionHandler({ AccessDeniedException.class })
public final ResponseEntity<Object> handleAccessDeniedException(
  Exception ex, WebRequest request) {
    return new ResponseEntity<Object>(
      "Access denied message here", new HttpHeaders(), HttpStatus.FORBIDDEN);
}

我有一个AOP,它应该在异常处理程序返回响应之后触发。

@AfterReturning(value="@annotation(exceptionHandler)",returning="response")  
public void afterReturningAdvice(JoinPoint joinPoint, Object response) {
//do something
}

但是在处理程序返回有效响应之后,不会触发@AfterReturning。

尝试使用全限定名,但不起作用

@AfterReturning(value = "@annotation(org.springframework.web.bind.annotation.ExceptionHandler)", returning = "response"){
public void afterReturningAdvice(JoinPoint joinPoint, Object response) {
  //do something
}

1 个答案:

答案 0 :(得分:1)

请通过documentation来了解Spring框架中的代理机制。

假设编写的ExceptionHandler代码具有以下格式

@ControllerAdvice
public class TestControllerAdvice {
    @ExceptionHandler({ AccessDeniedException.class })
    final public ResponseEntity<Object> handleAccessDeniedException(
      Exception ex, WebRequest request) {
        return new ResponseEntity<Object>(
          "Access denied message here", new HttpHeaders(), HttpStatus.FORBIDDEN);
    }
}
与该问题有关的文档中的

要点是

  1. Spring AOP使用JDK动态代理或CGLIB创建 给定目标对象的代理。

  2. 如果要代理的目标对象实现了至少一个 接口,使用JDK动态代理。所有接口 被目标类型实现的代理。如果目标对象 没有实现任何接口,则创建了CGLIB代理。

  3. 使用CGLIB,不能建议最终方法,因为不能在运行时生成的子类中覆盖它们。

  • OP根据评论和提示确定了问题,此答案供将来参考。