我们之前做AOP是直接拦截某个包下的所有方法,但是有的时候并非所有的方法都是需要进行AOP的,那么是否可以给定某个标识来进行 AOP呢?比如进行注解, 答案是可以的, 通过一个自定义注解,在 AOP里面根据那个方法加了注解来进行处理,别的不多说。直接上代码(前提需要了解一定的AOP知识以及注解式AOP方可阅读此文)
注解类:
import java.lang.annotation.*;
/**
*@Description: 获取程序执行时间(在需要使用的方法上面增加此注解)
*@Author: guanzhou.su, dont know what is mean? contact me at QQ:838951396, wechat:13824866769
*@Date: 2019/9/2
**/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface CountTime {
}
AOP 类:
/**
*@Description: 计算方法耗时
*@Author: guanzhou.su, dont know what is mean? contact me at QQ:838951396, wechat:13824866769
*@Date: 2019/9/2
**/
@Component
@Aspect
public class CountTimeAop {
@Pointcut("execution(* com.kds2.service.*.*(..))")
public void point() {
}
@Around("@annotation(countTime)")
public Object doAround(ProceedingJoinPoint pjp, CountTime countTime){
long startTime = System.currentTimeMillis();
Object obj = null;
try {
obj = pjp.proceed();
} catch (Throwable e) {
e.printStackTrace();
}
long endTime = System.currentTimeMillis();
MethodSignature signature = (MethodSignature) pjp.getSignature();
String methodName = signature.getDeclaringTypeName() + "." + signature.getName();
System.out.println("method [" + methodName + "] spend time: "+(endTime-startTime)+"ms");
return obj;
}
}
可以看到上面的 aoAround 方法是通过切点(point() 切点),针对 com.kds2.service 下的所有加上 @CountTime 注解的方法进行拦截, 在方法执行前后进行处理,并且计算时间
具体方法(com.kds2/service下的某个类的方法):
/**
*@Description: 测试
*@Param: [vo]
*@Author: guanzhou.su, dont know what is mean? contact me at QQ:838951396, wechat:13824866769
*@Date: 2019/8/30
*@return: com.kds2.resp.VoResp<java.lang.Void>
*
**/
@CountTime
public void test() {
System.out.println("test method");
}
打印结果:
test method
method [com.kds2.service.TblWeixinTemplateExtLogService.test] spend time: 72ms