程式設計式建立 @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>()
有關更多資訊,請參閱 javadoc。