java - 在访问多个 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) ?
解决方案
这似乎是您可以实现面向方面编程 (AOP) 的典型案例。如果您使用的是弹簧靴,那么您很容易实现它。对于初学者,您可以查看此链接:- https://www.springboottutorial.com/spring-boot-and-aop-with-spring-boot-starter-aop
您可能需要对其进行一些调整才能达到您的预期。但似乎可行。
推荐阅读
- javascript - Mongoose 参考集合或嵌套文档 2 级深度
- django - 基于类的视图中的 Django 错误消息
- vba - 突出显示包含 A 列 vba 中信息的每隔一行
- php - 使用 php 获取用户 Facebook 好友会引发异常
- java - 我的库没有检测到其 gradle 文件中提到的外部依赖项
- database - 如何更新在 oracle 中找到的值引用子记录
- git - .gitignore 没有按预期工作
- reactjs - Webpack 配置脚本不起作用
- sql-server - SQL Server:插入到链接服务器
- ldap - LDAP 和 OpenLDAP 有什么区别