一、AOP
AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。
二、AspectJ
AOP 是一种编程的思想,在具体的编程中需要实际的工具去实现这套思想。 AspectJ 就是这样的一个工具。AspectJ是一个面向切面编程的框架。AspectJ是对java的扩展,而且是完全兼容java的,AspectJ定义了AOP语法,它有一个专门的编译器用来生成遵守Java字节编码规范的Class文件。AspectJ还支持原生的Java,只需要加上AspectJ提供的注解即可。在Android开发中,一般就用它提供的注解和一些简单的语法就可以实现绝大部分功能上的需求了。
1,JoinPoint(连接点)
所谓连接点是指那些被拦截到的点
2,Pointcut(切入点)
所谓切入点是指我们要对哪些 Joinpoint 进行拦截的定义
3,Advice(通知)
所谓通知是指拦截到 Joinpoint 之后所要做的事情就是通知
4,Aspect(切面)
是切入点和通知(引介)的结合
Advice分类
Before:前置通知, 在目标执行之前执行通知
After:后置通知, 目标执行后执行通知
Around:环绕通知, 在目标执行中执行通知, 控制目标执行时机
AfterReturning:后置返回通知, 目标返回时执行通知
AfterThrowing:异常通知, 目标抛出异常时执行通知
@Aspect
public class BehaviorTraceAspect {
//定义切面的规则
//1、就再原来的应用中那些注解的地方放到当前切面进行处理
//execution(注解名 注解用的地方)
@Pointcut("execution(@com.highgreat.sven.myapplication.annotation.BehaviorTrace * *(..))")
public void methodAnnottatedWithBehaviorTrace(){
}
//2,对进入切面的内容如何处理
//@Before 在切入点之前运行
// @After("methodAnnottatedWithBehaviorTrace()")
//@Around 在切入点前后都运行
@Around("methodAnnottatedWithBehaviorTrace()")
public Object weaveJoinPoint(ProceedingJoinPoint joinPoint) throws Throwable{
MethodSignature methodSignature = (MethodSignature)joinPoint.getSignature();
String className = methodSignature.getDeclaringType().getSimpleName();
String methodName = methodSignature.getName();
String value = methodSignature.getMethod().getAnnotation(BehaviorTrace.class).value();
long begin = System.currentTimeMillis();
Object result = joinPoint.proceed();
SystemClock.sleep(new Random().nextInt(2000));
long duration = System.currentTimeMillis() - begin;
Log.d("alan", String.format("%s功能:%s类的%s方法执行了,用时%d ms",
value, className, methodName, duration));
return result;
}
}
JointPoint信息
在advice中我们可以拿到JointPoint的信息
JoinPoint.getSignature() 包含有
- MethodSignature 方法的签名
- FieldSignature 成员变量的签名
- ConstructorSignature 构造函数的签名
- InitializerSignature 初始化的签名
总结一下,使用AspectJ的步骤:
- 设置 Pointcut 的表达式
- 选择相应的 advice
- 对 JointPoint 或参数进行相应的处理
更多详细语法请参考官网
示例代码:
网友评论