除了使用 or 在配置中声明 aspects 之外,还可以以编程方式创建代理 通知目标对象。有关 Spring 的 AOP API 的完整详细信息,请参见下一章。在这里,我们想重点介绍自动 使用 @AspectJ 方面创建代理。<aop:config><aop:aspectj-autoproxy>spring-doc.cn

您可以使用 class 为一个或多个 @AspectJ 方面建议的目标对象创建代理。 此类的基本用法非常简单,如下例所示:org.springframework.aop.aspectj.annotation.AspectJProxyFactoryspring-doc.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.cn