问题描述
我有一个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);
}
@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
}
解决方法
请通过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);
}
}
与该问题有关的文档中的要点是
-
Spring AOP使用JDK动态代理或CGLIB创建 给定目标对象的代理。
-
如果要代理的目标对象实现了至少一个 接口,使用JDK动态代理。所有接口 被目标类型实现的代理。如果目标对象 没有实现任何接口,则创建了CGLIB代理。
-
使用CGLIB,不能建议最终方法,因为不能在运行时生成的子类中覆盖它们。
- OP根据评论和提示确定了问题,此答案供将来参考。