对于最新的稳定版本,请使用 Spring Framework 7.0.6!spring-doc.cadn.net.cn

使用ProxyFactory以编程方式创建AOP代理

使用Spring可以轻松地通过编程方式创建AOP代理。这使您可以在不依赖Spring IoC的情况下使用Spring AOP。spring-doc.cadn.net.cn

目标对象实现的接口会自动被代理。以下示例展示了为一个目标对象创建代理的过程,其中包含一个拦截器和一个通知:spring-doc.cadn.net.cn

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的对象。你可以使用目标对象创建它,如前面的例子所示,或者在另一个构造函数中指定要代理的接口。spring-doc.cadn.net.cn

您可以添加通知(拦截器作为一种特殊的通知类型)、切面或两者 并在 ProxyFactory 的生命周期内操作它们。如果添加 IntroductionInterceptionAroundAdvisor,则可以使代理实现额外的接口。spring-doc.cadn.net.cn

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.spring-doc.cadn.net.cn

将AOP代理创建与IoC框架集成是大多数应用程序中的最佳实践。我们建议您使用AOP将配置从Java代码中外部化,正如您通常应该做的那样。