宣告切面
啟用 @AspectJ 支援後,應用程式上下文中任何定義為 @AspectJ 切面(具有 @Aspect 註解)的 bean 都會被 Spring 自動檢測到,並用於配置 Spring AOP。以下兩個示例展示了一個不太有用的切面所需的最小步驟。
這兩個示例中的第一個展示了應用程式上下文中的常規 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 註解的類)可以像其他任何類一樣擁有方法和欄位。它們還可以包含切點、通知和引入(型別間)宣告。
|
透過元件掃描自動檢測切面 你可以透過 Spring XML 配置、@Configuration 類中的 @Bean 方法註冊切面類作為常規 bean,或者讓 Spring 透過類路徑掃描自動檢測它們 — 與任何其他 Spring 管理的 bean 相同。但是,請注意 @Aspect 註解不足以在類路徑中進行自動檢測。為此,你需要新增一個單獨的 @Component 註解(或者,根據 Spring 元件掃描器的規則,新增一個合格的自定義 stereotype 註解)。 |
|
用其他切面通知切面? 在 Spring AOP 中,切面本身不能成為其他切面的通知目標。類上的 @Aspect 註解將其標記為切面,因此將其排除在自動代理之外。 |