有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

首先,让我们考虑客户注册服务,简单地完成它的工作。

@Service
class CustomerRegister {
    private final CustomerRegister customerRegister;

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

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

后来决定,最好有一个关于注册表操作的业务度量。 常用的选择是使用org。springframework。靴子启动。韵律学。反服务

请注意:

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

如果我们决定调用

counterService.increment(REGISTY_METRIC);

在create方法的范围内,即使在事务回滚时,计数器也将增加

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

换句话说:

  1. 如何在另一个方面之上实现方面
  2. 如何在事务代理上实现方面

共 (1) 个答案

  1. # 1 楼答案

    按正常方式实现方面。只需确保自定义方面^{}设置为低值(即最高优先级,例如1),以便它在任何其他方面之前执行,在这种情况下,这是事务方面

    请参阅下图(reference)以图形化地理解请求流。通过在custom advisor(s)上设置适当的顺序,可以使其在事务通知之前/之后运行,而无需任何特殊考虑

    Spring Transaction execution flow

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