gpt4 book ai didi

java - 是否可以创建一个方面,对最初用@Transaction注释的方法提供@AfterReturnin操作?

转载 作者:行者123 更新时间:2023-12-02 12:11:58 25 4
gpt4 key购买 nike

首先让我们考虑一下,我们有 CustomerRegister 服务来完成其工作。

@Service
class CustomerRegister {
private final CustomerRegister customerRegister;

CustomerRegister(CustomerRegister customerRegister) {
this.customerRegister = customerRegister;
}

@Transactional
public void create(Customer customer) {
customerRegister.persist(customer);
}
}

后来我们决定拥有一个有关该注册表操作的业务指标可能会更好。常见的选择是使用 org.springframework.boot.actuate.metrics.CounterService

请注意:

Using @Transactional, Spring dynamically creates a proxy that implements the same interface(s) as the class you're annotating

如果我们决定调用

counterService.increment(REGISTY_METRIC);

在创建方法的范围内,即使事务回滚,计数器也会增加。

我的想法是创建一个方面来包装 transactional proxy (包装原始的 CustomerRegister 服务)。然后,@Aspect 组件可以提供用 @AfterReturning(pointcut = ) 注释的方法增量度量计数器。

其他的话:

  1. 如何在另一个方面上实现一个方面?
  2. 如何通过事务代理实现切面?

最佳答案

按照正常方式实现该方面。只需确保自定义方面' @Order设置为低值(即最高优先级,例如 1),以便它在任何其他方面(在本例中为事务方面)之前执行。

请参阅下图 ( reference ) 以图形方式了解请求流程。通过在自定义顾问程序上设置适当的顺序,可以使其在交易建议之前/之后运行,无需任何特殊考虑。

Spring Transaction execution flow

额外推荐阅读here了解 Spring 中方面排序的处理方式。

关于java - 是否可以创建一个方面,对最初用@Transaction注释的方法提供@AfterReturnin操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46472993/

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