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

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

问题描述

我有一个 Spring 应用程序,其中包含以下骨架类

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?

推荐答案

这就是 Ordered 接口用于.你需要在你的 bean 上实现它.

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天全站免登陆