@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; } } }