特性 | 说明 |
---|---|
基于注解 | 比传统XML配置更简洁 |
代理机制 | 运行时生成代理对象(JDK动态代理/CGLIB) |
连接点模型 | 支持方法执行、异常处理等多种切入点 |
@Aspect
@Component
@Order(1) // 控制多个切面的执行顺序
@Slf4j
public class LoggingAspect {
// 定义可重用的切入点表达式
@Pointcut("execution(* com.example.service.*.*(..))")
public void serviceLayer() {}
@Before("serviceLayer()")
public void logMethodStart(JoinPoint jp) {
log.info("▶️ 调用 {}.{} 参数: {}",
jp.getTarget().getClass().getSimpleName(),
jp.getSignature().getName(),
Arrays.toString(jp.getArgs()));
}
@Around("@annotation(com.example.audit.AuditLog)")
public Object auditLog(ProceedingJoinPoint pjp) throws Throwable {
long start = System.currentTimeMillis();
Object result = pjp.proceed();
log.info(" 审计日志 - 操作: {}, 耗时: {}ms",
pjp.getSignature().getName(),
System.currentTimeMillis() - start);
return result;
}
@AfterThrowing(pointcut = "serviceLayer()", throwing = "ex")
public void logException(JoinPoint jp, Exception ex) {
log.error("⚠️ 方法 {} 抛出异常: {}",
jp.getSignature(), ex.getMessage());
}
}
@Aspect
@Component
public class RateLimitAspect {
private final RateLimiter limiter = RateLimiter.create(100); // 100 QPS
@Around("@annotation(rateLimit)")
public Object limit(ProceedingJoinPoint pjp, RateLimit rateLimit)
throws Throwable {
if (!limiter.tryAcquire(rateLimit.timeout(), rateLimit.timeUnit())) {
throw new RateLimitException("请求过于频繁");
}
return pjp.proceed();
}
}
// 自定义注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface RateLimit {
long timeout() default 1;
TimeUnit timeUnit() default TimeUnit.SECONDS;
}
代理类型 | 条件 | 性能 | 限制 |
---|---|---|---|
JDK动态代理 | 目标实现接口 | 较高 | 只能代理接口方法 |
CGLIB代理 | 无接口类 | 略低 | 无法代理final方法 |
代理选择逻辑:
// Spring AbstractAutoProxyCreator 的核心逻辑
if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
return JdkDynamicAopProxy();
}
return ObjenesisCglibAopProxy();
精确切入点匹配
// 不推荐(扫描范围过大)
@Pointcut("execution(* *(..))")
// 推荐(限定包路径+注解)
@Pointcut("execution(* com.yourpackage..service.*.*(..)) && " +
"@annotation(org.springframework.transaction.annotation.Transactional)")
避免切面内部耗时操作
@Around("serviceLayer()")
public Object profile(ProceedingJoinPoint pjp) throws Throwable {
// 错误示范:在切面内进行数据库操作
// auditRepository.save(...);
// 正确做法:只做轻量级记录
long start = System.nanoTime();
Object result = pjp.proceed();
long duration = System.nanoTime() - start;
metrics.record(duration);
return result;
}
@Aspect
@Component
public class TransactionRetryAspect {
@Around("@annotation(retry)")
public Object retry(ProceedingJoinPoint pjp, RetryOnConflict retry)
throws Throwable {
int attempts = 0;
do {
try {
return pjp.proceed();
} catch (OptimisticLockingFailureException ex) {
if (++attempts >= retry.maxAttempts()) throw ex;
Thread.sleep(retry.backoff());
}
} while (true);
}
}
public class OrderService {
public void createOrder() {
this.updateStock(); // 自调用不走代理!
}
@Transactional
public void updateStock() {...}
}
解决方案:
((OrderService) context.getBean("orderService")).updateStock();
((OrderService) AopContext.currentProxy()).updateStock();
现象:A切面依赖B服务,B服务又需要被A切面代理
解决:
@DependsOn("bService") // 强制初始化顺序
@Aspect
@Component
public class AAspect {
@Autowired
private BService bService;
}
# application.properties
spring.aop.proxy-target-class=true # 强制使用CGLIB
logging.level.org.springframework.aop=DEBUG
@Aspect
@Component
public class AopMonitorAspect {
@Around("within(@org.aspectj.lang.annotation.Aspect *)")
public Object monitorAspect(ProceedingJoinPoint pjp) throws Throwable {
String aspectName = pjp.getTarget().getClass().getSimpleName();
Monitor.start("aop.aspect." + aspectName);
try {
return pjp.proceed();
} finally {
Monitor.end();
}
}
}
特性 | Spring AOP | AspectJ |
---|---|---|
织入时机 | 运行时 | 编译期/类加载期 |
性能 | 有代理开销 | 无运行时损耗 |
能力 | 仅方法级别 | 支持字段、构造器等 |
<plugin>
<groupId>org.codehaus.mojogroupId>
<artifactId>aspectj-maven-pluginartifactId>
<executions>
<execution>
<goals>
<goal>compilegoal>
goals>
execution>
executions>
plugin>