面向方面编程的异常处理

时间:2021-07-22 14:59:54

标签: java spring spring-boot aspectj aspect

我是面向方面编程的新手。我正在使用 AspectJ 开发一个 spring-boot 应用程序,它已经有一个异常处理方面,如下所示:

@Aspect
@Order(0)
public class ExceptionAspect {
 

  public ExceptionAspect() {
  }

  @Pointcut("within(com.mycom.service.impl..*)")
  public void applicationServicePointcut() {
  }

  @AfterThrowing(
    pointcut = "applicationServicePointcut()",
    throwing = "e"
  )
  public void translate(JoinPoint joinPoint, Throwable e) {
    ...
     //EXCEPTION HANDLING LOGIC
  }
}

现在我想再添加一个方面,对与上述相同的切入点说 NewAspect,即

  "within(com.mycom.service.impl..*)"

此外,我希望 NewAspect 中发生的任何异常都由 ExceptionAspect 处理。

在这方面,我无法理解,新方面的Order是否应该超过现有的ExceptionAspect

1 个答案:

答案 0 :(得分:1)

@Order 注释或实现 @Ordered 接口是 Spring 特定的,因此仅对 Spring 管理的组件有效。 AspectJ 是独立于 Spring 的产品。它有自己的声明和处理优先级的方式:

  • AspectJ programming guide 中搜索一般术语“优先级”,特别是 declare precedence 语句。

  • 虽然之前的文档解释了基础知识以及如何在原生 AspectJ 语法中声明优先级,但请在 AspectJ 5 developer's notebook 中搜索 @DeclarePrecedence 以了解注释语法替代方案。

P.S.:我问你是使用原生 AspectJ 还是 Spring AOP 是因为排序注释,还因为在 Spring AOP 中,一个方面不能建议另一个方面。所以你想要的只有在原生 AspectJ 中才有可能。