宣告 Aspect

啟用 @AspectJ 支援後,在您的應用程式 Context 中定義的任何 Bean,只要其類別是 @AspectJ Aspect(具有 @Aspect 註解),Spring 就會自動偵測到,並用於配置 Spring AOP。接下來的兩個範例展示了一個不太實用的 Aspect 所需的最少步驟。

以下第一個範例展示了應用程式 Context 中的常規 Bean 定義,該定義指向一個使用 @Aspect 註解的 Bean 類別

  • Java

  • Kotlin

  • Xml

public class ApplicationConfiguration {

	@Bean
	public NotVeryUsefulAspect myAspect() {
		NotVeryUsefulAspect myAspect = new NotVeryUsefulAspect();
		// Configure properties of the aspect here
		return myAspect;
	}
}
class ApplicationConfiguration {

	@Bean
	fun myAspect() = NotVeryUsefulAspect().apply {
		// Configure properties of the aspect here
	}
}
<bean id="myAspect" class="org.springframework.docs.core.aop.ataspectj.aopataspectj.NotVeryUsefulAspect">
	<!-- configure properties of the aspect here -->
</bean>

以下第二個範例展示了 NotVeryUsefulAspect 類別定義,該類別使用 @Aspect 註解

  • Java

  • Kotlin

@Aspect
public class NotVeryUsefulAspect {
}
@Aspect
class NotVeryUsefulAspect

Aspect(使用 @Aspect 註解的類別)可以像任何其他類別一樣,擁有方法和欄位。它們還可以包含切入點、通知和引介(介面類型)宣告。

透過組件掃描自動偵測 Aspect
您可以將 Aspect 類別註冊為 Spring XML 配置中的常規 Bean,透過 @Configuration 類別中的 @Bean 方法,或讓 Spring 透過類別路徑掃描自動偵測它們,這與任何其他 Spring 管理的 Bean 相同。但是,請注意,@Aspect 註解不足以在類別路徑中進行自動偵測。為此,您需要新增一個單獨的 @Component 註解(或替代地,一個符合 Spring 組件掃描器規則的自訂原型註解)。
使用其他 Aspect 通知 Aspect 嗎?
在 Spring AOP 中,Aspect 本身不能成為來自其他 Aspect 的通知目標。類別上的 @Aspect 註解將其標記為 Aspect,因此將其排除在自動代理之外。