1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| package aop;
import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*;
@Aspect public class CallAdvice { public static int steps = 1;
@Pointcut("execution(* service.*.*(..))") public void fooPointcut() {}
@Before("execution(* service.*.*(..))") public void doBefore(JoinPoint jp) { String className = jp.getTarget().getClass().getName(); String methodName = jp.getSignature().getName(); System.out.println(String.format("[%d: BEFORE METHOD]: %s.%s()", steps++, className, methodName)); }
@After("fooPointcut()") public void doAfter(JoinPoint jp) { String className = jp.getTarget().getClass().getName(); String methodName = jp.getSignature().getName(); System.out.println(String.format("[%d: AFTER METHOD]: %s.%s()\n", steps++, className, methodName)); }
@Around("fooPointcut()") public Object doAround(ProceedingJoinPoint pjp) throws Throwable { String className = pjp.getTarget().getClass().getName(); String methodName = pjp.getSignature().getName(); int sn = steps++;
System.out.println(String.format("[%d: METHOD BEFORE]: %s.%s()", sn, className, methodName));
long time = System.currentTimeMillis(); Object retVal = pjp.proceed(); time = System.currentTimeMillis() - time;
System.out.println(String.format("[%d: METHOD AFTER]: %s.%s() : %dms\n", sn, className, methodName, time));
return retVal; }
@AfterThrowing(pointcut="fooPointcut()", throwing="error") public void doThrowing(JoinPoint jp, Throwable error) { String className = jp.getTarget().getClass().getName(); String methodName = jp.getSignature().getName(); System.out.println(String.format("[%d: THROW EXCEPTION]: %s.%s()\n", steps++, className, methodName)); System.out.println(error.getMessage()); } }
|