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

@AspectJ 代理的编程式创建

除了通过使用 <aop:config><aop:aspectj-autoproxy> 在配置中声明切面之外,还可以以编程方式创建代理来对目标对象进行增强。有关 Spring AOP API 的完整详情,请参阅下一章。在这里,我们重点关注如何使用 @AspectJ 切面自动创建代理。spring-doc.cadn.net.cn

你可以使用 org.springframework.aop.aspectj.annotation.AspectJProxyFactory 类 为一个目标对象创建代理,该目标对象由一个或多个 @AspectJ 切面进行增强。 此类的基本用法非常简单,如下例所示:spring-doc.cadn.net.cn

// create a factory that can generate a proxy for the given target object
AspectJProxyFactory factory = new AspectJProxyFactory(targetObject);

// add an aspect, the class must be an @AspectJ aspect
// you can call this as many times as you need with different aspects
factory.addAspect(SecurityManager.class);

// you can also add existing aspect instances, the type of the object supplied
// must be an @AspectJ aspect
factory.addAspect(usageTracker);

// now get the proxy object...
MyInterfaceType proxy = factory.getProxy();
// create a factory that can generate a proxy for the given target object
val factory = AspectJProxyFactory(targetObject)

// add an aspect, the class must be an @AspectJ aspect
// you can call this as many times as you need with different aspects
factory.addAspect(SecurityManager::class.java)

// you can also add existing aspect instances, the type of the object supplied
// must be an @AspectJ aspect
factory.addAspect(usageTracker)

// now get the proxy object...
val proxy = factory.getProxy<Any>()

有关更多信息,请参阅javadocspring-doc.cadn.net.cn