@Aspect
public class LoggingAspect {
@Pointcut("execution(* com.example.myapp.service.*.*(..))")
private void serviceMethods() {}
@Before("serviceMethods()")
public void logBefore(JoinPoint joinPoint) {
System.out.println("Before method execution: " + joinPoint.getSignature().getName());
}
@AfterReturning(pointcut = "serviceMethods()", returning = "returnValue")
public void logAfterReturning(JoinPoint joinPoint, Object returnValue) {
System.out.println("After method execution: " + joinPoint.getSignature().getName() + ", return value: " + returnValue);
}
@Around("serviceMethods()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
long startTime = System.currentTimeMillis();
Object result = joinPoint.proceed();
long endTime = System.currentTimeMillis();
System.out.println("Method execution time: " + (endTime - startTime) + " ms");
return result;
}
}
以上代码表示一个名为 LoggingAspect 的切面类,其中 @Aspect 注解表示这是一个切面类。在类中定义了一个名为 serviceMethods 的切点,表示所有位于 com.example.myapp.service 包下的任意方法都会被拦截。具体实现了三个建议(advice):前置通知(@Before)、返回通知(@AfterReturning)、环绕通知(@Around)。
@Before 注解的方法 logBefore 会在匹配到切点之前执行,并将 JoinPoint 对象作为参数传入,通过该对象可以获取拦截到的方法信息,例如方法名等。
@AfterReturning 注解的方法 logAfterReturning 会在匹配到切点并且拦截的方法正常返回时执行,并将 JoinPoint 对象和返回值作为参数传入。
@Around 注解的方法 logAround 会在匹配到切点之前和之后执行,并且需要手动调用 ProceedingJoinPoint 对象的 proceed 方法来执行被拦截的方法。同时,该方法可以通过计时器统计方法执行时间,并返回被拦截方法的返回值。