代理機制

Spring AOP 使用 JDK 動態代理或 CGLIB 為給定的目標物件建立代理。JDK 動態代理內置於 JDK 中,而 CGLIB 是一個常見的開源類定義庫(已重新打包到 `spring-core` 中)。

如果要代理的目標物件實現至少一個介面,則使用 JDK 動態代理,並且代理目標型別實現的所有介面。如果目標物件不實現任何介面,則建立 CGLIB 代理,它是目標型別的執行時生成的子類。

如果你想強制使用 CGLIB 代理(例如,代理目標物件上定義的每個方法,而不僅僅是其介面實現的方法),你可以這樣做。但是,你應該考慮以下問題:

  • `final` 類不能被代理,因為它們不能被繼承。

  • `final` 方法不能被增強,因為它們不能被覆蓋。

  • `private` 方法不能被增強,因為它們不能被覆蓋。

  • 不可見的方法——例如,父類中來自不同包的包私有方法——不能被增強,因為它們實際上是私有的。

  • 由於 CGLIB 代理例項是透過 Objenesis 建立的,因此你的代理物件的建構函式不會被呼叫兩次。但是,如果你的 JVM 不允許繞過建構函式,你可能會看到雙重呼叫以及 Spring AOP 支援對應的除錯日誌條目。

  • 你的 CGLIB 代理使用可能會面臨 Java 模組系統的限制。典型情況下,在模組路徑上部署時,你不能為 `java.lang` 包中的類建立 CGLIB 代理。這種情況需要一個 JVM 引導標誌 `--add-opens=java.base/java.lang=ALL-UNNAMED`,而這個標誌對於模組是不可用的。

要強制使用 CGLIB 代理,將 `<aop:config>` 元素的 `proxy-target-class` 屬性設定為 true,如下所示:

<aop:config proxy-target-class="true">
	<!-- other beans defined here... -->
</aop:config>

當你使用 @AspectJ 自動代理支援時,要強制使用 CGLIB 代理,將 `<aop:aspectj-autoproxy>` 元素的 `proxy-target-class` 屬性設定為 `true`,如下所示:

<aop:aspectj-autoproxy proxy-target-class="true"/>

多個 `<aop:config/>` 片段在執行時會合併成一個統一的自動代理建立器,該建立器會應用任何一個 `<aop:config/>` 片段(通常來自不同的 XML bean 定義檔案)指定的最強代理設定。這也適用於 `<tx:annotation-driven/>` 和 `<aop:aspectj-autoproxy/>` 元素。

需要明確的是,在 `<tx:annotation-driven/>`、`<aop:aspectj-autoproxy/>` 或 `<aop:config/>` 元素上使用 `proxy-target-class="true"` 會強制所有這三個元素都使用 CGLIB 代理。

理解 AOP 代理

Spring AOP 是基於代理的。在你編寫自己的切面或使用 Spring Framework 提供的任何基於 Spring AOP 的切面之前,理解最後這句話的實際含義至關重要。

首先考慮一個普通、未被代理的物件引用的場景,如下面的程式碼片段所示:

  • Java

  • Kotlin

public class SimplePojo implements Pojo {

	public void foo() {
		// this next method invocation is a direct call on the 'this' reference
		this.bar();
	}

	public void bar() {
		// some logic...
	}
}
class SimplePojo : Pojo {

	fun foo() {
		// this next method invocation is a direct call on the 'this' reference
		this.bar()
	}

	fun bar() {
		// some logic...
	}
}

如果你呼叫物件引用上的方法,該方法將直接在該物件引用上被呼叫,如下圖和列表所示:

aop proxy plain pojo call
  • Java

  • Kotlin

public class Main {

	public static void main(String[] args) {
		Pojo pojo = new SimplePojo();
		// this is a direct method call on the 'pojo' reference
		pojo.foo();
	}
}
fun main() {
	val pojo = SimplePojo()
	// this is a direct method call on the 'pojo' reference
	pojo.foo()
}

當客戶端程式碼持有的引用是代理時,情況會略有不同。考慮下面的圖和程式碼片段:

aop proxy call
  • Java

  • Kotlin

public class Main {

	public static void main(String[] args) {
		ProxyFactory factory = new ProxyFactory(new SimplePojo());
		factory.addInterface(Pojo.class);
		factory.addAdvice(new RetryAdvice());

		Pojo pojo = (Pojo) factory.getProxy();
		// this is a method call on the proxy!
		pojo.foo();
	}
}
fun main() {
	val factory = ProxyFactory(SimplePojo())
	factory.addInterface(Pojo::class.java)
	factory.addAdvice(RetryAdvice())

	val pojo = factory.proxy as Pojo
	// this is a method call on the proxy!
	pojo.foo()
}

這裡需要理解的關鍵是,`Main` 類中 `main(..)` 方法內部的客戶端程式碼持有一個對代理的引用。這意味著在該物件引用上的方法呼叫是針對代理的呼叫。因此,代理可以將呼叫委託給與該特定方法呼叫相關的所有攔截器(通知)。然而,一旦呼叫最終到達目標物件(在本例中是 `SimplePojo` 引用),它可能對自身進行的任何方法呼叫,例如 `this.bar()` 或 `this.foo()`,都將針對 `this` 引用而不是代理進行呼叫。這具有重要的影響。這意味著自呼叫不會導致與方法呼叫關聯的通知有機會執行。換句話說,透過顯式或隱式的 `this` 引用進行的自呼叫將繞過通知。

為了解決這個問題,你有以下選項。

避免自呼叫

最好的方法(這裡的“最好”只是一個籠統的說法)是重構你的程式碼,以便不會發生自呼叫。這確實需要你做一些工作,但它是最好的、侵入性最小的方法。

注入自引用

另一種方法是利用自注入,並透過自引用而不是透過 this 呼叫代理上的方法。

使用 AopContext.currentProxy()

最後這種方法強烈不推薦使用,我們傾向於前兩種選項,不願指出此方法。然而,作為最後的手段,你可以選擇將類中的邏輯與 Spring AOP 繫結,如下面的示例所示。

  • Java

  • Kotlin

public class SimplePojo implements Pojo {

	public void foo() {
		// This works, but it should be avoided if possible.
		((Pojo) AopContext.currentProxy()).bar();
	}

	public void bar() {
		// some logic...
	}
}
class SimplePojo : Pojo {

	fun foo() {
		// This works, but it should be avoided if possible.
		(AopContext.currentProxy() as Pojo).bar()
	}

	fun bar() {
		// some logic...
	}
}

使用 AopContext.currentProxy() 會將你的程式碼完全耦合到 Spring AOP,並且使類本身知道它正在 AOP 上下文中使用,這會降低 AOP 的部分優勢。它還要求配置 ProxyFactory 以暴露代理,如下面的示例所示:

  • Java

  • Kotlin

public class Main {

	public static void main(String[] args) {
		ProxyFactory factory = new ProxyFactory(new SimplePojo());
		factory.addInterface(Pojo.class);
		factory.addAdvice(new RetryAdvice());
		factory.setExposeProxy(true);

		Pojo pojo = (Pojo) factory.getProxy();
		// this is a method call on the proxy!
		pojo.foo();
	}
}
fun main() {
	val factory = ProxyFactory(SimplePojo())
	factory.addInterface(Pojo::class.java)
	factory.addAdvice(RetryAdvice())
	factory.isExposeProxy = true

	val pojo = factory.proxy as Pojo
	// this is a method call on the proxy!
	pojo.foo()
}
AspectJ 編譯時織入和載入時織入沒有這種自呼叫問題,因為它們是在位元組碼內部應用通知,而不是透過代理。