|
对于最新的稳定版本,请使用 Spring Framework 7.0.6! |
以编程方式创建 @AspectJ 代理
除了通过使用<aop:config>或<aop:aspectj-autoproxy>在配置中声明切面,还可以通过编程方式创建代理来通知目标对象。有关Spring的AOP API的完整详细信息,请参见下一章。在这里,我们希望专注于使用@AspectJ切面自动创建代理的能力。
您可以使用org.springframework.aop.aspectj.annotation.AspectJProxyFactory类
为一个或多个@AspectJ切面建议的目标对象创建代理。
这个类的基本用法非常简单,如下例所示:
-
Java
-
Kotlin
// 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>()
请参阅Java文档以获取更多信息。