@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