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

Is it possible to create an Aspect that provides @AfterReturnin operation on method that was originally annotated with @Transaction?

首先让我们考虑一下我们有 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);

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

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

换句话说:

  1. 如何在另一个方面实现方面?
  2. 如何实现 aspect over transactional 代理?

像往常一样实施方面。只需确保自定义方面的 @Order 设置为低值(,即最高优先级,例如 1),以便它在事务方面的任何其他方面之前执行这种情况。

参考下图 (reference) 以图形方式理解请求流程。通过在 custom advisor(s) 上设置适当的顺序,可以在交易建议之前/之后进行 运行,无需任何特殊考虑。

额外推荐阅读 here 以了解 Spring 中如何处理方面排序。