Declaring an Aspect
如果启用了 @AspectJ 支持,应用程序上下文中的任何 bean 都采用了带有 @Aspect
批注(带有 @Aspect
批注)的 @AspectJ 方面类的 bean,Spring 会自动检测到它们,并可用于配置 Spring AOP。以下两个示例显示并非十分有用的方面所需的最小步骤。
With @AspectJ support enabled, any bean defined in your application context with a
class that is an @AspectJ aspect (has the @Aspect
annotation) is automatically
detected by Spring and used to configure Spring AOP. The next two examples show the
minimal steps required for a not-very-useful aspect.
这两个示例中,第一个示例显示应用程序上下文中带有常规定义的 bean,它指向用 @Aspect
做批注的 bean 类:
The first of the two examples shows a regular bean definition in the application context
that points to a bean class that is annotated with @Aspect
:
-
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>
这两个示例中,第二个示例显示带有 @Aspect
做批注的 NotVeryUsefulAspect
类定义:
The second of the two examples shows the NotVeryUsefulAspect
class definition, which is
annotated with @Aspect
:
-
Java
-
Kotlin
@Aspect
public class NotVeryUsefulAspect {
}
@Aspect
class NotVeryUsefulAspect
(带有 @Aspect
做批注的)方面(类)可以具有与任何其他类相同的方法和字段。它们还可以包含切入点、建议和引入(中间类型)声明。
Aspects (classes annotated with @Aspect
) can have methods and fields, the same as any
other class. They can also contain pointcut, advice, and introduction (inter-type)
declarations.
Autodetecting aspects through component scanning
您可以在Spring XML配置中将aspect类注册为常规bean,通过`@Configuration`类中的`@Bean`方法注册,或者让Spring通过类路径扫描自动检测它们,就像其他Spring托管的bean一样。但是,请注意, |
Autodetecting aspects through component scanning
You can register aspect classes as regular beans in your Spring XML configuration,
via |
Advising aspects with other aspects?
在Spring AOP中,aspect本身不能成为其他aspect的advice目标。类上的`@Aspect`注释将其标记为aspect,因此,将其排除在自动代理之外。 |
Advising aspects with other aspects?
In Spring AOP, aspects themselves cannot be the targets of advice from other
aspects. The |