在Spring中指定代理创建的顺序 [英] Specifying the order of proxy creation in Spring

查看:51
本文介绍了在Spring中指定代理创建的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Spring Application,其中有以下骨架类

I have a Spring Application where I have the following skeleton class

class ServiceCaller
{
    public Result callService()
    {
        //call a remote service
    }
}

由于调用远程服务是一项昂贵的操作,因此我在应用程序中添加了缓存.我使用了EhCache Spring批注 @Cacheable 并将其应用于了 callService()方法.一切工作正常,我的 Result 对象得到了正确的缓存.

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.

稍后,我想在所有 ServiceCaller 上添加一个记录器,以便记录器可以记录对远程服务的每次实际调用.我不想将 logger.info()手动添加到每个这样的 callService 方法中,所以我决定使用Spring AOP来实现这一点.

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.

我在返回要记录的所有方法后定义了切入点.它在工作;但是我注意到,即使我遇到缓存命中并且没有调用实际的 callService 方法,也会调用记录器切入点.我观察到,发生这种情况是因为我对 ServiceCaller bean的代理顺序如下: AOPPointCutProxy(EhCacheCachingProxy(ServiceCallerBean)).我希望仅在调用实际的 callService 方法时调用记录器切入点,而不是在从EhCache代理返回缓存值时调用记录器切入点.这意味着我实际上希望我的代理创建层次结构采用 EhCacheCachingProxy(AOPPointCutProxy(ServiceCallerBean))的形式.请注意,我的bean定义,切入点定义,缓存配置都可能位于不同的随机命名的xml文件中.

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.

那么我该如何强制Spring以我想要的顺序创建代理?

So how do I enforce Spring to create the proxies in the order I want?

推荐答案

这就是

That is what the Ordered interface is used for. You need to implement that on your beans.

您可以创建一个代理,该代理将获取所有应该围绕您调用的代理注入.只有该复合代理围绕实际的bean.调用后,它将按指定的顺序调用注入的代理.

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.

这篇关于在Spring中指定代理创建的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆