@Aspect public class CalculatorLoggingAspect { private Log log = LogFactory.getLog(this.getClass()); @Before("execution(* ArithmeticCalculator.add(..))") public void logBefore() { log.info("The method add() begins"); } }
@Aspect public class CalculatorLoggingAspect { ... ... @Before("execution(* *.*(..))") public void logBefore(JoinPoint joinPoint) { log.info("The method " + joinPoint.getSignature().getName()+ "() begins with " + Arrays.toString(joinPoint.getArgs())); } }
@Aspect public class CalculatorLoggingAspect { ... @After("execution(* *.*(..))") public void logAfter(JoinPoint joinPoint) { log.info("The method " + joinPoint.getSignature().getName() + "() ends"); } }
@Aspect public class CalculatorLoggingAspect { ... ... @AfterReturning("execution(* *.*(..))") public void logAfterReturning(JoinPoint joinPoint) { log.info("The method " + joinPoint.getSignature().getName()+ "() ends"); } }
能夠在@ AfterReturning註解中添加returning,在通知中添加Object類型的參數獲取方法的返回信息:
@Aspect public class CalculatorLoggingAspect { ... ... @AfterReturning(pointcut = "execution(* *.*(..))", returning = "result") public void logAfterReturning(JoinPoint joinPoint, Object result) { log.info("The method " + joinPoint.getSignature().getName()+ "() ends with " + result); } }
@Aspect public class CalculatorLoggingAspect { ... ... @AfterThrowing("execution(* *.*(..))") public void logAfterThrowing(JoinPoint joinPoint) { log.error("An exception has been thrown in "+ joinPoint.getSignature().getName() + "()"); } }
能夠經過在 @AfterThrowing 中添加throwing獲取異常,在通知中添加Throwable類型的參數:
@Aspect public class CalculatorLoggingAspect { ... ... @AfterThrowing(pointcut = "execution(* *.*(..))", throwing = "e") public void logAfterThrowing(JoinPoint joinPoint, Throwable e) { log.error("An exception " + e + " has been thrown in "+ joinPoint.getSignature().getName() + "()"); } }
能夠經過在通知中指定異常類型,來只捕獲特定類型的異常:
@Aspect public class CalculatorLoggingAspect { ... ... @AfterThrowing(pointcut = "execution(* *.*(..))", throwing = "e") public void logAfterThrowing(JoinPoint joinPoint,IllegalArgumentException e) { log.error("Illegal argument " + Arrays.toString(joinPoint.getArgs())+ " in " + joinPoint.getSignature().getName() + "()"); } }
@Aspect public class CalculatorLoggingAspect { ... @Around("execution(* *.*(..))") public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable { log.info("The method " + joinPoint.getSignature().getName()+ "() begins with " + Arrays.toString(joinPoint.getArgs())); try { Object result = joinPoint.proceed(); log.info("The method " + joinPoint.getSignature().getName()+ "() ends with " + result); return result; } catch (IllegalArgumentException e) { log.error("Illegal argument "+ Arrays.toString(joinPoint.getArgs()) + " in "+ joinPoint.getSignature().getName() + "()"); throw e; } } }