Spring AOP:After vs After返回优先级
我编写了以下代码片段:Spring AOP:After vs After返回优先级,spring,spring-boot,spring-aop,Spring,Spring Boot,Spring Aop,我编写了以下代码片段: @Aspect @Component public class ApiAuditAspect { @Pointcut(value = "execution(* net.gencat.transversal.espaidoc.api.controller.RepositoryController.*(..))") public void anyRepositoryController() { // Nothing to do here
@Aspect
@Component
public class ApiAuditAspect {
@Pointcut(value = "execution(* net.gencat.transversal.espaidoc.api.controller.RepositoryController.*(..))")
public void anyRepositoryController() {
// Nothing to do here
}
@AfterReturning(
pointcut = "anyRepositoryController()",
returning = "result")
public void audit(JoinPoint point, Object result) throws Throwable {
// audit actions
}
@After("anyRepositoryController()")
public void flush() {
// flush all audits
}
}
我意识到flush
是在audit
之前执行的
我认为@After
是在返回后执行的
关于如何解决这个问题,你有什么想法吗?在文档中,这两个建议的执行顺序和优先级都没有。
事实上,他们不应该一起使用
返回后应在方法毫无例外地返回时使用
当方法引发异常时,应使用后throwing
应使用之后的,而不是前两种,并且需要处理这两种情况
因此,我建议您去掉其中一个,并在返回其他代码之后使用make flush调用,如果您需要在异常情况下执行此操作,请使用@afterhrowing调用相同的方法添加其他通知。
或者对于同一类中定义的方面,默认情况下仅使用@After和distinct这两种可能的情况。他们的执行没有秩序。但是,如果您希望对方面进行排序,那么每个方面都应该在一个单独的类中,并且应该使用@order注释声明顺序,如下所示
@Order(1)
public class MyAudit{
@AfterReturning(
pointcut = "anyRepositoryController()",
returning = "result")
public void audit(JoinPoint point, Object result) throws Throwable {
// audit actions
}
}
@Order(6)
public class MyFlush{
@After("anyRepositoryController()")
public void flush() {
// flush all audits
}
}
首先选择最小值,这可以是负值,因为顺序是从Integer.MIN\u值到Integer.MAX\u值定义的。另一件事是,如果您定义了多个具有相同顺序值的类,那么无法保证从Spring 5.2开始,对于具有相同顺序值的类,将首先选择哪个类。(于2020年6月9日发布)在同一方面类中的任何@AfterReturn或@AfterThrowing通知方法之后调用@AfterAdvice方法
来自:当在同一方面中定义的两条通知都需要在同一连接点上运行时,顺序是未定义的解决方案/解决方法也在文档中指定。这和克劳斯在回答中提到的一样