Creating AOP Proxies Programmatically with the ProxyFactory

利用 Spring 可以轻松以编程方式创建 AOP 代理。这让你可以在不依赖 Spring IoC 的情况下使用 Spring AOP。

It is easy to create AOP proxies programmatically with Spring. This lets you use Spring AOP without dependency on Spring IoC.

目标对象实现的接口会被自动代理。以下列表展示了一个代理的创建,该代理针对一个目标对象,包含一个拦截器和一个 Advisor:

The interfaces implemented by the target object are automatically proxied. The following listing shows creation of a proxy for a target object, with one interceptor and one advisor:

  • Java

  • Kotlin

ProxyFactory factory = new ProxyFactory(myBusinessInterfaceImpl);
factory.addAdvice(myMethodInterceptor);
factory.addAdvisor(myAdvisor);
MyBusinessInterface tb = (MyBusinessInterface) factory.getProxy();
val factory = ProxyFactory(myBusinessInterfaceImpl)
factory.addAdvice(myMethodInterceptor)
factory.addAdvisor(myAdvisor)
val tb = factory.proxy as MyBusinessInterface

第一步是构建一个 org.springframework.aop.framework.ProxyFactory 类型的对象。你可以在前一个示例中使用一个目标对象创建,或者在备用构造器中指定要代理的接口。

The first step is to construct an object of type org.springframework.aop.framework.ProxyFactory. You can create this with a target object, as in the preceding example, or specify the interfaces to be proxied in an alternate constructor.

你可以在 ProxyFactory 的生命周期中添加建议(以拦截器作为一种特殊类型的建议)、Advisor 或同时添加建议和 Advisor 并对其进行操作。如果你添加了一个 IntroductionInterceptionAroundAdvisor,你可以让代理实现附加接口。

You can add advice (with interceptors as a specialized kind of advice), advisors, or both and manipulate them for the life of the ProxyFactory. If you add an IntroductionInterceptionAroundAdvisor, you can cause the proxy to implement additional interfaces.

ProxyFactory(继承自 AdvisedSupport)中还有一些便利方法,这些方法允许你添加其他通知类型,如前置通知和抛出通知。AdvisedSupportProxyFactoryProxyFactoryBean 的超类。

There are also convenience methods on ProxyFactory (inherited from AdvisedSupport) that let you add other advice types, such as before and throws advice. AdvisedSupport is the superclass of both ProxyFactory and ProxyFactoryBean.

在大多数应用程序中,将 AOP 代理创建与 IoC 框架集成是最佳实践。我们建议使用 AOP 从 Java 代码中提取配置,你通常也应该这样做。

Integrating AOP proxy creation with the IoC framework is best practice in most applications. We recommend that you externalize configuration from Java code with AOP, as you should in general.