gpt4 book ai didi

aspectj - Spring AOP : @AfterThrowing execution pointcut never matches

转载 作者:行者123 更新时间:2023-12-02 22:02:49 24 4
gpt4 key购买 nike

我对 AOP 完全陌生。我需要建议来编写正确的切入点。我有一个包含所有服务类的服务包。所有类都实现了 Service界面。这个接口(interface)有一个方法 save(entity) .我的建议应该在每次 service.save(entity) 时执行方法抛出 DataIntegrityViolationException .

这里的方面:

@Component
@Aspect
public class DIVExceptionHandler {
@AfterThrowing(pointcut = "execution(* myPackage.service.Service.save(*))", throwing = "ex")
public void handleException(JoinPoint joinPoint, DataIntegrityViolationException ex) {
//snipped
}
}

Spring AOP documentation 中所述,我在 CP 中有两个 aspectj jar我添加了 <aop:aspectj-autoproxy/>到 Spring 配置,我正在使用组件扫描。在测试日志中,我可以看到该方面被检测为 aspetcj 方面:

DEBUG o.s.a.a.a.ReflectiveAspectJAdvisorFactory - Found AspectJ method...

所以我相信这不是配置问题,我的切入点表达式是错误的。我也试过了

@AfterThrowing(pointcut = "execution(* myPackage.service.*.save(*))", throwing = "ex")

但这也不起作用。

那么正确的切入点表达式是什么?

最佳答案

这实际上是一个配置问题。

@AfterThrowing(pointcut = "execution(* myPackage.service.Service.save(*))", throwing = "ex")

工作正常。

实际问题是 DataIntegrityViolationException 仅在 @Transactional 的代理完成交易后抛出。就我而言,这是在可以调用我的建议之后发生的。

解决方案是在事务配置中添加订单属性:

<tx:annotation-driven transaction-manager="transactionManager" order="2000"/>

然后向您的切面添加一个小于事务注释的 @Order 注释:

@Component
@Order(1500) // must be less than order of <tx:annotation-driven />
@Aspect
public class DIVExceptionHandler {
@AfterThrowing(pointcut = "execution(* myPackage.service.Service.save(*))", throwing = "ex")
public void handleException(JoinPoint joinPoint, DataIntegrityViolationException ex) {
//snipped
}
}

参见:

Spring AOP ordering - Transactions before Advise

关于aspectj - Spring AOP : @AfterThrowing execution pointcut never matches,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16603061/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com