以程式設計方式建立 @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