问题
I have a Spring Application where I have the following skeleton class
class ServiceCaller
{
public Result callService()
{
//call a remote service
}
}
Since calling a remote service is an expensive operation, I added caching in my application. I used EhCache Spring annotations @Cacheable
and applied it to the callService()
method. Everything was working fine and my Result
objects were getting correctly cached.
Later I wanted to add a logger across all my ServiceCaller
s such that my logger would record every actual call to a remote service. I did not want to manually add logger.info()
to every such callService
method so I decided to use a Spring AOP to implement this.
I defined a pointcut after-returning to all the methods that I wanted to log. It was working; however I noticed that my logger point cut was invoked even when I had a cache hit and my actual callService
method was not called. This, I observed, was happening because the order of my proxy to the ServiceCaller
bean was as follows: AOPPointCutProxy(EhCacheCachingProxy(ServiceCallerBean))
. I want my logger pointcut to be invoked only when my actual callService
method is called and not when it is returning with a cached value from the EhCache proxy. Which means that I actually want my proxy creation hierarchy to be in the form of EhCacheCachingProxy(AOPPointCutProxy(ServiceCallerBean))
. Note that my bean definitions, pointcut definitions, cache configs may all be in different randomly named xml files.
So how do I enforce Spring to create the proxies in the order I want?
回答1:
That is what the Ordered interface is used for. You need to implement that on your beans.
You can create a proxy that gets all of the proxies injected that should surround you call. Only that composite proxy surrounds the actual bean. Upon invocation it calls the injected proxies in their specified order.
来源:https://stackoverflow.com/questions/15840954/specifying-the-order-of-proxy-creation-in-spring