首页 > 解决方案 > 在访问多个 JpaRepositories 之前和之后运行函数

问题描述

我有几个用@Repository 注释并扩展JpaRepository 的接口。它们都在我的项目中的同一个包中。

@Repository
public interface CustomerRepository extends JpaRepository<CustomerDTO>{
    List<CustomerDTO> findByKeyCustomerId(long customerId);
    List<CustomerDTO> findByKeyCustomerIdAndName(long customerId, String name);
}

@Repository
public interface UpdateRepository extends JpaRepository<UpdateDTO> {
  @Query(value = "select nextval('sq')", nativeQuery = true)
  Integer getNextUpdateId();
}

我在代码中间的项目中的不同包中的许多不同位置使用存储库的方法。

customerRepository.findByKeyCustomerId(customerId);
customerRepository.save(customerEntry);
updateRepository.getNextUpdateId();
updateRepository.save(updateEntry);

我想在上述所有这些调用之前调用相同的方法,并在这些调用之后调用另一个相同的方法。

private void before(Span span) {
   span.annotate("Before");
}

private void after(Span span) {
   span.annotate("After");
}

我想模拟以下代码:

span.annotate("Before");
Integer updateId = updateRepository.getNextUpdateId(); //can be any other repository method
span.annotate("After");

如何以通用方式实现这一点,而无需在调用存储库接口方法的代码中的任何地方插入 before(span) 和 after(span) ?

标签: javaspringoopjpaspring-data-jpa

解决方案


这似乎是您可以实现面向方面编程 (AOP) 的典型案例。如果您使用的是弹簧靴,那么您很容易实现它。对于初学者,您可以查看此链接:- https://www.springboottutorial.com/spring-boot-and-aop-with-spring-boot-starter-aop

您可能需要对其进行一些调整才能达到您的预期。但似乎可行。


推荐阅读