典型用法
第1步:定义切面类(Aspect)
使用 @Aspect 注解标记一个类为切面类,并结合 @Component 或 @Service 注册为 Spring Bean。
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class LoggingAspect {
// 定义切点:拦截 com.example.service 包下所有方法
@Before("execution(* com.example.service.*.*(..))")
public void logMethodCall() {
System.out.println("【AOP】方法开始执行...");
}
}
第2步:启用 AspectJ 自动代理
XML 配置方式(适用于传统 Spring 项目)
如果你使用的是 XML 配置方式,可以这样启用 AspectJ 自动代理
<aop:aspectj-autoproxy />
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
Java 注解配置方式(适用于 Spring 项目)
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configuration
@EnableAspectJAutoProxy
public class AopConfig {
}
@EnableAspectJAutoProxy(proxyTargetClass = true) // true:强制使用 CGLIB 代理(默认为 JDK 动态代理)。
Spring Boot 方式(最简化)
只需添加依赖,并将切面类标注为 @Aspect + @Component,即可自动生效。不需要手动添加 @EnableAspectJAutoProxy。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>