Programmatic Creation of @AspectJ Proxies
除了使用 <aop:config>
或 <aop:aspectj-autoproxy>
在你的配置中声明方面之外,还可以以编程方式创建建议目标对象的代理。有关 Spring 的 AOP API 的详细信息,请参见 next chapter。在这里,我们要关注使用 @AspectJ 方面自动创建代理的能力。
In addition to declaring aspects in your configuration by using either <aop:config>
or <aop:aspectj-autoproxy>
, it is also possible to programmatically create proxies
that advise target objects. For the full details of Spring’s AOP API, see the
next chapter. Here, we want to focus on the ability to automatically
create proxies by using @AspectJ aspects.
您可以使用`org.springframework.aop.aspectj.annotation.AspectJProxyFactory`类为由一个或多个@AspectJ切面建议的目标对象创建一个代理。此类的基本用法非常简单,如下例所示:
You can use the org.springframework.aop.aspectj.annotation.AspectJProxyFactory
class
to create a proxy for a target object that is advised by one or more @AspectJ aspects.
The basic usage for this class is very simple, as the following example shows:
-
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>()
有关详细信息,请参见https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/aop/aspectj/annotation/AspectJProxyFactory.html[javadoc]。
See the javadoc for more information.