Specifying the order of proxy creation in Spring

浪子不回头ぞ 提交于 2021-01-03 05:27:34

问题


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 ServiceCallers 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!