package org.bk.inventory.aspect; import org.bk.inventory.types.Inventory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public aspect AuditAspect { private static Logger logger = LoggerFactory.getLogger(AuditAspect.class); pointcut serviceMethods() : execution(* org.bk.inventory.service.*.*(..)); pointcut serviceMethodsWithInventoryAsParam(Inventory inventory) : execution(* org.bk.inventory.service.*.*(Inventory)) && args(inventory); before() : serviceMethods() { logger.info("before method"); } Object around() : serviceMethods() { long start = System.nanoTime(); Object result = proceed(); long end = System.nanoTime(); logger.info(String.format("%s took %d ns", thisJoinPointStaticPart.getSignature(), (end - start))); return result; } Object around(Inventory inventory) : serviceMethodsWithInventoryAsParam(inventory) { Object result = proceed(inventory); logger.info(String.format("WITH PARAM: %s", inventory.toString())); return result; } after() : serviceMethods() { logger.info("after method"); } }
This maps to the previously defined @AspectJ notation
Since this is a DSL specifically for defining Aspects, it is not understood by the java compiler. AspectJ provides a tool(ajc) to compile these native aspectj files and to weave the aspects into the targeted pointcuts. Maven provides a plugin which seamlessly invokes ajc at the point of compilation:
<plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>aspectj-maven-plugin</artifactId> <version>1.0</version> <dependencies> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>${aspectj.version}</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjtools</artifactId> <version>${aspectj.version}</version> </dependency> </dependencies> <executions> <execution> <goals> <goal>compile</goal> <goal>test-compile</goal> </goals> </execution> </executions> <configuration> <outxml>true</outxml> <aspectLibraries> <aspectLibrary> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> </aspectLibrary> </aspectLibraries> <source>1.6</source> <target>1.6</target> </configuration> </plugin>
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