SpringAop的一些实用知识点
Joinpoint
-
Signature getSignature():获取封装了署名信息的对象,在该对象中可以获取到目标方法名,所属类的Class等信息
* joinPoint.getSignature().getName()获取到方法名信息
* joinPoint.getSignature().getDeclaringType() 获取到类.所调用的方法中的 类,即调用方法的类,之后再考虑使用类加载器反射来完成需要的 -
Object[] getArgs();获取传入目标方法的参数对象
-
Object getTarget();获取被代理的对象(对象的声明类型)
-
Object getThis();获取代理对象(对象的实例类型)
Proceedingjoinpoint
- 只能用在around通知里
- Object proceed() throws Throwable:执行目标方法
- Object proceed(Object[] var1) throws Throwable:传入参数执行目标方法
@PointCut注解
- 就俩个参数 value,argNames
- @Before @AfterReturning @Around里面的都有value,argNames参数
简单的实战,通过切面统计方法执行时间
@Around("@annotation(countTime)")
public Object running (ProceedingJoinPoint pjp, CountTime countTime) throws Throwable {
long beginTime = System.currentTimeMillis();
Object obj = pjp.proceed(); //执行目标方法
String methodName = pjp.getSignature().getName(); //方法名字
String className = pjp.getSignature().getDeclaringTypeName(); //类的名字
long endTime = System.currentTimeMillis();
log.info(className + "中->" + methodName + "方法共计耗时:{}", (endTime - beginTime) + " ms");
return obj;
}
CountTime注解如下
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface CountTime {
}