声明切面
启用 @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 注解将其标记为切面,因此将其排除在自动代理之外。 |