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 | package org.bk.inventory.aspect; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Aspect public class AuditAspect { private static Logger logger = LoggerFactory.getLogger(AuditAspect. class ); @Pointcut ( "execution(* org.bk.inventory.service.*.*(..))" ) public void serviceMethods(){ // } @Before ( "serviceMethods()" ) public void beforeMethod() { logger.info( "before method" ); } @Around ( "serviceMethods()" ) public Object aroundMethod(ProceedingJoinPoint joinpoint) { try { long start = System.nanoTime(); Object result = joinpoint.proceed(); long end = System.nanoTime(); logger.info(String.format( "%s took %d ns" , joinpoint.getSignature(), (end - start))); return result; } catch (Throwable e) { throw new RuntimeException(e); } } @After ( "serviceMethods()" ) public void afterMethod() { logger.info( "after method" ); } } |
The @Aspect annotation on the class identifies it as an aspect definition. It starts by defining the pointcuts:
1 2 | @Pointcut ( "execution(* org.bk.inventory.service.*.*(..))" ) public void serviceMethods(){} |
1 | <bean id= "auditAspect" class = "org.bk.inventory.aspect.AuditAspect" /> |
Links to all sessions on AOP:
AOP Session 1 - Decorator Pattern using Java Dynamic Proxies
AOP Session 2 - Using Spring AOP - xml based configuration
AOP Session 3 - Using Spring AOP - @AspectJ based configuration - with/without compile time weaving
AOP Session 4 - Native AspectJ with compile time weaving
AOP Session 5 - Comprehensive Example
No comments:
Post a Comment