此版本仍在开发中,尚不被认为是稳定的。对于最新的稳定版本,请使用 Spring Framework 6.2.10spring-doc.cadn.net.cn

声明方面

启用@AspectJ支持后,在应用程序上下文中定义的任何 bean 类,该类是@AspectJ方面(具有@Aspect注释)自动 被 Spring 检测到并用于配置 Spring AOP。接下来的两个示例显示了 对于不太有用的方面,需要最少的步骤。spring-doc.cadn.net.cn

两个示例中的第一个示例显示了应用程序上下文中的常规 Bean 定义 指向一个用@Aspect:spring-doc.cadn.net.cn

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:spring-doc.cadn.net.cn

@Aspect
public class NotVeryUsefulAspect {
}
@Aspect
class NotVeryUsefulAspect

方面(用@Aspect) 可以有方法和字段,与任何 其他类。它们还可以包含切入点、建议和介绍(inter-type) 声明。spring-doc.cadn.net.cn

通过组件扫描自动检测各个方面
您可以在 Spring XML 配置中将 aspect 类注册为常规 bean, 通过@Bean方法@Configuration类,或者让 Spring 通过 类路径扫描 — 与任何其他 Spring 管理的 Bean 相同。但是,请注意@Aspect注释不足以在类路径中进行自动检测。为此 目的,您需要添加一个单独的@Component注释(或者,或者,自定义 stereotype 注释,根据 Spring 的组件扫描程序的规则)。
将方面与其他方面提供建议?
在 Spring AOP 中,方面本身不能成为来自其他方面建议的目标 方面。这@Aspect类上的注释将其标记为一个方面,因此排除 它来自自动代理。