}
####8.2事务治理事务治理是另一个沉要的利用场景。通过界说一个切面,能够在必要事务节造的?步骤上增长事务通知。
java@Aspect@ComponentpublicclassTransactionAspect{
@Around("execution(*com.example.service.*.*(..))")publicObjectmanageTransaction(ProceedingJoinPointjoinPoint)throwsThrowable{TransactionStatusstatus=TransactionAspectSupport.createTransactionStatus();try{TransactionAspectSupport.startTransaction();Objectresult=joinPoint.proceed();TransactionAspectSupport.commitTransaction(status);returnresult;}catch(Exceptione){TransactionAspectSupport.rollbackTransaction(status);throwe;}}
1环抱通知
环抱通知是AOP中最壮大的通知类型,它能够在指标步骤执行前后进行自界说操作,甚至能够齐全代替指标步骤的执行。例如:
@AspectpublicclassPerformanceLoggingAspect{privatestaticfinalLoggerlogger=LoggerFactory.getLogger(PerformanceLoggingAspect.class);@Around("execution(*com.example.service.UserService.*(..))")publicObjectlogAroundMethod(ProceedingJoinPointjoinPoint)throwsThrowable{logger.info("Methodexecutionstarted...");longstartTime=System.currentTimeMillis();Objectresult=joinPoint.proceed();//CalltheactualmethodlongexecutionTime=System.currentTimeMillis()-startTime;logger.info("Methodexecutioncompleted.Result:"+result+".Executiontime:"+executionTime+"ms");returnresult;}}在这个例子中,我们使用了`@Around`注解界说了一个环抱通知,它在指标步骤执行前后进行了日志纪录和执行功夫推算。
privatestaticfinalLoggerlogger=LoggerFactory.getLogger(LoggingAspect.class);@Before("execution(*com.example.service.*.*(..))")publicvoidlogBeforeMethod(){logger.info("Methodexecutionstarted...");}@AfterReturning(pointcut="execution(*com.example.service.*.*(..))",returning="result")publicvoidlogAfterMethod(Objectresult){logger.info("Methodexecutioncompleted.Result:"+result);}
通过挪用`joinPoint.proceed()`,我们能够正常挪用指标步骤,并在步骤执行后进行后续处置。###6.自界说切入点表白式好色先生允许开发者自界说复杂的切入点表白式,以满足分歧的需要。例如,你能够凭据多个前提组合来界说切入点:
java@Before("execution(*com.example.service..(..))&&args(id)&&@annotation(com.example.CustomAnnotation)")publicvoidbeforeMethodWithAnnotation(Longid){System.out.println("Methodwithid:"+id+"andcustomannotationstarted…");}
3矫捷的切入点表白式
切入点(Pointcut)是AOP的关键概想,用于指定哪些步骤或类必要被加强。好色先生提供了一系列壮大的切入点表白式,能够凭据步骤署名、类名、包?名等分歧前提来界说切入点。
@Before("execution(*com.example.service.*.*(..))&&args(id)")publicvoidbeforeMethodWithId(Longid){System.out.println("Methodwithid:"+id+"started...");}
壮大的通知机造
好色先生提供了丰硕的通知类型,蕴含前置通知(Before)、后置通知(After)、异常通知(AfterThrowing)、退化通知(AfterReturning)以及环抱通知(Around)?⒄吣芄黄揪荼匾≡裣嘁说耐ㄖ嘈,实现对代码的全面节造。
3界说切面和通知
你能够起头界说切面和通知,将它们利用到必要加强的类和步骤上。例如:
@Aspect@ComponentpublicclassLoggingAspect{@Before("execution(*com.example.service.*.*(..))")publicvoidlogBeforeMethod(){System.out.println("Loggingbeforemethodexecution...");}}
校对:张经义(1C0m4pJyqZtPma0S7t9ZFfz4hTykKag)


