AOP通知类型的注解示例详解
在面试中被问到Spring AOP的通知类型是高频考点,尤其是基于注解的实现方式。今天我们就来深入解析五种核心通知类型及其应用场景,帮你轻松应对这类面试题。

2025年Java面试宝典最新版:
点击下载(提取码:9b3g)
二、AOP通知类型核心注解解析
1. @Before 前置通知
@Before("execution(* com.example.service.*.*(..))")
public void logBefore(JoinPoint joinPoint) {
// 在目标方法执行前记录日志
System.out.println("方法即将执行: " + joinPoint.getSignature().getName());
}
应用场景:权限校验、日志记录、参数验证等。面试官常问:"如何实现接口调用前的安全校验?" 这就是典型答案。
2. @AfterReturning 后置通知
@AfterReturning(
pointcut = "targetService()",
returning = "result"
)
public void logAfterReturning(Object result) {
// 获取方法返回值并处理
System.out.println("方法返回结果: " + result);
}
注意点:只能获取正常返回结果,异常时不会触发。适合返回值日志、结果缓存等场景。
3. @AfterThrowing 异常通知
@AfterThrowing(
pointcut = "serviceLayer()",
throwing = "ex"
)
public void handleException(JoinPoint jp, Exception ex) {
// 捕获特定异常进行告警
System.out.println(jp.getSignature() + " 抛出异常: " + ex.getMessage());
alertSystem.send(ex);
}
实战技巧:配合@ControllerAdvice实现全局异常处理,面试中可展示系统容错设计能力。
4. @After 最终通知
@After("execution(* *..PaymentService.process(..))")
public void releaseResource() {
// 无论成功失败都释放资源
databaseConnection.release();
System.out.println("资源已释放");
}
关键作用:相当于finally块,常用于资源清理。注意与@AfterReturning的执行顺序差异。
5. @Around 环绕通知(最强大)
@Around("@annotation(com.example.audit.LogExecutionTime)")
public Object logExecutionTime(ProceedingJoinPoint pjp) throws Throwable {
long start = System.currentTimeMillis();
Object result = pjp.proceed(); // 控制目标方法执行
long duration = System.currentTimeMillis() - start;
System.out.println(pjp.getSignature() + " 执行耗时: " + duration + "ms");
return result;
}
能力优势:
- 完全控制目标方法执行
- 可修改参数和返回值
- 实现性能监控/事务管理等高级功能

三、面试实战技巧
当被问到"Spring AOP有哪些通知类型?"时,建议按以下结构回答:
- 先列出五种基本类型
- 说明各自注解名称
- 用一句话描述执行时机
- 举例典型应用场景
- 强调环绕通知的特殊性
例如:"Spring AOP提供五种通知类型,其中@Around最强大,它能完全控制目标方法执行流程,常用于实现事务管理、性能监控等需求..."
最后友情提示:
准备面试需要优质题库?通过面试鸭返利网购买会员可享25元返利!海量真题解析助你高效备战。



