½ç˵һ¸öÇÐÃæÀ´´¦ÀíÈÕÖ¾¼Í¼ºÍÖ´ÐÐʱ¼äÅÌË㣺
@Aspect@ComponentpublicclassPerformanceLoggingAspect{privatestaticfinalLoggerlogger=LoggerFactory.getLogger(PerformanceLoggingAspect.class);@Before("execution(*com.example.service.UserService.*(..))")publicvoidlogBeforeMethod(){logger.info("Methodexecutionstarted...");}@AfterReturning(pointcut="execution(*com.example.service.UserService.*(..))",returning="result")publicvoidlogAfterMethod(Objectresult){longexecutionTime=System.currentTimeMillis()-startTime;logger.info("Methodexecutioncompleted.Result:"+result+".Executiontime:"+executionTime+"ms");}}
}
####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);}
2Ç¿´óµÄ֪ͨ»úÖÆ
֪ͨ£¨Advice£©ÊÇAOPµÄ½¹µã¿´·¨¡£ºÃÉ«ÏÈÉúÖ§³Ö¶àÖÖÀàÐ͵Ä?֪ͨ£¬ÈçǰÖÃ֪ͨ£¨Before£©¡¢ºóÖÃ֪ͨ£¨After£©¡¢·µ»ØÍ¨Öª£¨AfterReturning£©¡¢Ò쳣֪ͨ£¨AfterThrowing£©µÈ?¡£ÀýÈ磺
@After("execution(*com.example.service.*.*(..))")publicvoidafterMethod(){System.out.println("Methodexecutioncompleted.");}
У¶Ô£ºÖì¹ãȨ(1C0m4pJyqZtPma0S7t9ZFfz4hTykKag)


