Overview of AspectJ style AOP
Please refer to spring-framework under org.springframework.mylearntest package for code related to this article (from official source spring-test module).
No need to implement corresponding interfaces like in 1.0, the only thing to do is to add an @Aspect annotation on this Aspect class. This way we can determine which classes in ClassPath are Aspect definitions we are looking for. Define Pointcut via @Pointcut, specify which methods define corresponding Advice logic via annotations like Around.
PerformanceTraceAspect
package org.springframework.mylearntest.aop2.aspectj;
import org.apache.commons.lang3.time.StopWatch;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
/**
* @Author: whalefall
* @Date: 2020/7/28 22:46
* After Spring 2.0 no need to implement interfaces to define pointcut
*/
@Aspect
public class PerformanceTraceAspect {
private final Log logger = LogFactory.getLog(PerformanceTraceAspect.class);
@Pointcut("execution(public void *.method1()) || execution(public void *.method2())")
public void pointcutName() {}
@Around("pointcutName()")
public Object performanceTrace(ProceedingJoinPoint joinPoint) throws Throwable {
StopWatch sw = new StopWatch();
try {
sw.start();
return joinPoint.proceed();
} finally {
System.out.println("pt in method["
+ joinPoint.getSignature().getName()
+ "]>>>>>>" + sw.toString());
}
}
}
Agreement
The code part of this work is licensed under Apache License 2.0 . You may freely modify and redistribute the code, and use it for commercial purposes, provided that you comply with the license. However, you are required to:
- Attribution: Retain the original author's signature and code source information in the original and derivative code.
- Preserve License: Retain the Apache 2.0 license file in the original and derivative code.
- Attribution: Give appropriate credit, provide a link to the license, and indicate if changes were made.
- NonCommercial: You may not use the material for commercial purposes. For commercial use, please contact the author.
- ShareAlike: If you remix, transform, or build upon the material, you must distribute your contributions under the same license as the original.