声明一个方面
启用 @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
Aspects(用 @Aspect
注解的类)可以拥有方法和字段,与其他类相同。它们还可以包含切入点、通知和引介(交叉类型)声明。
备注
通过组件扫描自动检测切面
你可以在 Spring XML 配置中将切面类注册为常规 bean,通过 @Configuration
类中的 @Bean
方法,或者让 Spring 通过类路径扫描自动检测它们——与任何其他 Spring 管理的 bean 相同。然而,请注意,@Aspect
注解不足以在类路径中进行自动检测。为此,你需要添加一个单独的 @Component
注解(或者,作为替代,符合 Spring 组件扫描器规则的自定义构造型注解)。
备注
建议方面与其他方面?
在 Spring AOP 中,方面本身不能成为其他方面建议的目标。类上的 @Aspect
注解将其标记为一个方面,因此将其排除在自动代理之外。