Search code examples
javaspringspring-mvcaop

Data retrieval optimization using AOP in a REST service


I'm implementing a REST service using Spring MVC (Spring Boot) and I'm creating some Aspects to handle some cross functionalities of the service.

An example is a service method like this:

public void doSomethingWithUser(int userId){
    // retrieve user from DB and do something...
}

and in my Aspect class a method like this:

@Around("execution(* com.test.myrestsvc.services.MyService.doSomethingWithUser(..))")
public void aroundDoSomething(ProceedingJoinPoint pjp) throws Throwable {
    // retrieve user (the same retrieved in the method) and do something else...
}

As you can see, I have two methods doing different things with the same user object, so I have to execute the same query two times even if the user is already retrieved in the main method.

Note that for certain methods in my service layer I have several aspects triggered by a single method invocation, this multiply the user retrieval several times.

So I'm wondering: is there a way to share objects at least among aspects in a REST (stateless) application? Can you suggest a different approach to minimize data access in these situations?


Solution

  • You can try to use Spring level caching, here is simple tutorial, but be careful and pay additional attention on cache eviction policies.

    If you're using Spring Data JPA with Hibernate or EclipseLink, you can also try to enable second level caching in your JPA implementation provider: Example