九游体育官方平台 - JIUYOUSPORTS中文官网:日志记录与监控
在大?多数项目中,日志记录和监控是不可或缺的功能。通过性巴克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");}}}
九游体育官方平台 - JIUYOUSPORTS中文官网:后置返回通知(AfterReturning)
在目标?方法成功执行后,但在我们对结果进行任何处理之前执行。
@Aspect@ComponentpublicclassPostExecutionLoggingAspect{@AfterReturning(pointcut="execution(*com.example.service.*.*(.*))",returning="result")publicvoidlogAfterReturning(JoinPointjoinPoint,Objectresult){System.out.println("后置返回通知:方法"+joinPoint.getSignature().getName()+"返回值:"+result);}}
九游体育官方平台 - JIUYOUSPORTS中文官网:核心概念
切面(Aspect):包含了横切关注点的?代码。它是AOP的?基本单元。连接点(JoinPoint):程序执行过程中可切入的点,如方法调用、异常抛出等。切入点(Pointcut):定义在哪些连接点应用切面的规则。通知(Advice):实际在连接点上执行的代码,可以是前置通知、后置通知、异常通知等。
九游体育官方平台 - JIUYOUSPORTS中文官网:事务管理
事务管理是数据库操作中常见的需求。通过性巴通过性巴克AOP,我们可以在不修改业务代码的情况下,确保事务的正确性和一致性。
@AspectpublicclassTransactionAspect{@Around("execution(*com.example.service.*.*(..))")publicObjectmanageTransaction(ProceedingJoinPointjoinPoint)throwsThrowable{TransactionStatusstatus=TransactionAspect.transactionManager.getTransaction(newDefaultTransactionDefinition());try{Objectresult=joinPoint.proceed();transactionManager.commit(status);returnresult;}catch(Exceptione){transactionManager.rollback(status);throwe;}}}
校对:王小丫(1C0m4pJyqZtPma0S7t9ZFfz4hTykKag)


