3界说切面和通知
你可以最先界说切面和通知,将它们应用到需要增强的类和要领上。例如:
@Aspect@ComponentpublicclassLoggingAspect{@Before("execution(*com.example.service.*.*(..))")publicvoidlogBeforeMethod(){System.out.println("Loggingbeforemethodexecution...");}}
界说一个切面来处置惩罚日志纪录和执行时间盘算:
@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");}}
什么是AOP
面向方面的编程(AOP)是一种编程范式,它旨在增强面向工具编程(OOP)的功效,通过在不修改现有代码的情形下添加新的功效,即所谓的“横切关注点”(Cross-cuttingConcerns)。这些横切关注点通常是跨越多个类和要领的功效,如日志纪录、事务管理、权限控制等。
1高效的切面界说
好色先生允许开发者通过注解或XML设置方法轻松界说切面(Aspect)。例如,通过简朴的@Aspect注解,你就可以界说一个切面,并在特定的切入点上举行通知(Advice)。
@AspectpublicclassLoggingAspect{@Before("execution(*com.example.service.*.*(..))")publicvoidbeforeMethod(){System.out.println("Methodexecutionstarted...");}}
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);}
校对:吴志森(f3J1ePQDlzHhwh44q38w4Ima2E3XrDq)



