春季的ProxyFactoryBean [英] ProxyFactoryBean in Spring
问题描述
有人可以解释 ProxyFactoryBean 简单来说?
Can someone explain ProxyFactoryBean in simple terms?
我看到很多地方都引用了它.
I see this being quoted lot of places.
推荐答案
ProxyFactoryBean
用于将拦截器逻辑应用于现有目标Bean,以便在调用该Bean上的方法时,拦截器在-和-之前执行.在该方法调用之后.这是面向方面编程(AOP)的示例.
ProxyFactoryBean
is used to apply interceptor logic to an existing target bean, so that when methods on that bean are invoked, the interceptors are executed before-and-after that method call. This is an example of Aspect Oriented Programming (AOP).
最好用一个简单的例子来解释. AOP的经典用例是将缓存应用于方法调用的结果.可以使用ProxyFactoryBean
将其连接起来,如下所示:
This is best explained using a simple example. A classic use-case for AOP is to apply caching to the result of a method call. This could be wired up using ProxyFactoryBean
as follows:
<bean id="targetService" class="com.x.MyClass"/>
<bean id="cachingInterceptor" class="com.x.MyCachingInterceptor"/>
<bean id="cachedService" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target" ref="targetService"/>
<property name="interfaces">
<list>
<value>com.x.MyService</value>
</list>
</property>
<property name="interceptorNames">
<list>
<value>cachingInterceptor</value>
</list>
</property>
</bean>
我们有一个类型为com.x.MyClass
的bean targetService
,它实现了接口com.x.MyService
.我们还有一个名为cachingInterceptor
的拦截器bean,它实现了接口org.aopalliance.intercept.MethodInterceptor
.
We have a bean targetService
of type com.x.MyClass
, which implements the interface com.x.MyService
. We also have a interceptor bean called cachingInterceptor
, which implements the interface org.aopalliance.intercept.MethodInterceptor
.
此配置将生成一个名为cachedService
的新bean,该bean实现MyService
接口.任何对该对象上方法的调用都将首先通过cachingInterceptor
对象的invoke()
方法传递,在这种情况下,该方法将在其内部缓存中查找先前方法调用的结果.它将返回缓存的结果,或者允许方法调用继续进行targetService
上的适当方法.
This config will generate a new bean, called cachedService
, which implements the MyService
interface. Any calls to the methods on that object will first be passed through the cachingInterceptor
object's invoke()
method, which in this case would look for the results of previous method calls in its internal cache. It would either return the cached result, or allow the method call to proceed to the appropropriate method on targetService
.
targetService
本身对此一无所知,它完全不了解正在发生的所有AOP问题.
targetService
itself knows nothing of this, it's completely unaware of all this AOP stuff going on.
ProxyFactoryBean
在Spring内部被大量使用以生成代理(由于各种原因(例如,远程存根,事务管理)),但它也非常适合在应用程序逻辑中使用.
ProxyFactoryBean
is heavily used internally within Spring to generate proxies for a variety of reasons (e.g. remoting stubs, transaction management), but it's perfectly suitable for use in application logic also.
这篇关于春季的ProxyFactoryBean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!