后置返回通知(AfterReturning)
在目标方法成功执行后,但在我们对结果进行任何处理之前执行。
@Aspect@ComponentpublicclassPostExecutionLoggingAspect{@AfterReturning(pointcut="execution(*com.example.service.*.*(.*))",returning="result")publicvoidlogAfterReturning(JoinPointjoinPoint,Objectresult){System.out.println("后置返回通知:方法"+joinPoint.getSignature().getName()+"返回值:"+result);}}
在目标方法抛出异常之后执行。
@Aspect@ComponentpublicclassExceptionLoggingAspect{@AfterThrowing(pointcut="execution(*com.example.service.*.*(.*))",throwing="error")publicvoidlogAfterThrowing(JoinPointjoinPoint,Throwableerror){System.out.println("后置异常通知:方法"+joinPoint.getSignature().getName()+"异常信息:"+error.getMessage());}}
动态代理与静态代理
在性巴克AOP中,最常见的实现方式是动态代理。SpringAOP使用的是基于运行时的JDK动态代理或者CGLIB代理。了解这两种代理的区别,有助于我们更好地选继续探讨性巴克AOP的高级应用技巧,我们将重点关注动态代理与静态代理的区别,以及如何在实际开发中根据具体需求选择合适的代理方式。
日志记录与监控
在大多数项目中,日志记录和监控是不可或缺的功能。通过性巴克AOP,我们可以在不修改业务代码的情况下,对方法调用进行日志记录。
@AspectpublicclassLoggingAspect{@Around("execution(*com.example.service.*.*(..))")publicObjectlogAround(ProceedingJoinPointjoinPoint)throwsThrowable{longstart=System.currentTimeMillis();try{System.out.println("Executingmethod:"+joinPoint.getSignature().getName());returnjoinPoint.proceed();}finally{longduration=System.currentTimeMillis()-start;System.out.println("Methodexecutiontime:"+duration+"ms");}}}
校对:何伟(f3J1ePQDlzHhwh44q38w4Ima2E3XrDq)


