Running Function Before and After Accessing Several JpaRepositories

Amir :

I have several interfaces which annotated with @Repository and extends JpaRepository. All of them are in same package in my project.

@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();
}

I use the methods of the repositories in many different places in different packages in my project in middle of the code.

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

I want to call the same method before all of these calls above and call another same method after these calls.

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

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

I want to simulate the following code:

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

How can I achieve that in generic way, without inserting before(span) and after(span) everywhere in code where I call the methods of repository interfaces?

CovetousSlope :

This seems like a typical case where you can implement aspect oriented programming (AOP). If you are using spring boot then it would be very easy for you to implement it. For a starter you can check this link :- https://www.springboottutorial.com/spring-boot-and-aop-with-spring-boot-starter-aop

You may have to tune it a bit to achieve what you are expecting. But seems doable.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=299816&siteId=1