小试牛刀--Android AOP(面向切面编程)开发

AOP面向切面编程开发

说明

定义

把某方面的功能提出来与一批对象进行隔离,这样与一批对象之间降低耦合性,就可以对某个功能进行编程。

应用
  • 用户行为统计
  • 权限管理
  • 其他
AOP实现流程
  • aspectj 框架

是一个面向切面编程框架,它有专门的编译器用来生成java 字节 码,生成class文件。我们使用这个框架后编译字节码的工具不再试javac

下载aspectj 地址: http://www.eclipse.org/aspectj/downloads.php
下载aspectj的adt地址: http://www.eclipse.org/ajdt/downloads/#43zips
aspectJ 写法: http://fernandocejas.com/2014/08/03/aspect-oriented-programming-in-android/

  • 实现流程

    • 标记切点

      用注解实现一个标识,添加到需要使用地方

    • 在切面中处理切点

      用AspectJ来实现切点的逻辑

    • 逻辑处理

  • 优点
    因为用了自己编译器生成class文件,所以注解发生在编译时,对java性能无任何影响。

编码实现

此处我们使用AOP实现方法耗时统计

Android studio添加AspectJ框架

  • 更改module的build 文件
//需要添加
import org.aspectj.bridge.IMessage
import org.aspectj.bridge.MessageHandler
import org.aspectj.tools.ajc.Main

apply plugin: 'com.android.application'

buildscript {
    repositories {
        mavenCentral()
    }
    //需要添加
    dependencies {
        classpath 'org.aspectj:aspectjtools:1.8.9'
        classpath 'org.aspectj:aspectjweaver:1.8.9'
    }
}
repositories {
    mavenCentral()
}
android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.siqiyan.lightlu.aoptest"
        minSdkVersion 23
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
//需要添加
final def log = project.logger
final def variants = project.android.applicationVariants
variants.all { variant ->
    if (!variant.buildType.isDebuggable()) {
        log.debug("Skipping non-debuggable build type '${variant.buildType.name}'.")
        return;
    }

    JavaCompile javaCompile = variant.javaCompile
    javaCompile.doLast {
        String[] args = ["-showWeaveInfo",
                         "-1.8",
                         "-inpath", javaCompile.destinationDir.toString(),
                         "-aspectpath", javaCompile.classpath.asPath,
                         "-d", javaCompile.destinationDir.toString(),
                         "-classpath", javaCompile.classpath.asPath,
                         "-bootclasspath", project.android.bootClasspath.join(File.pathSeparator)]
        log.debug "ajc args: " + Arrays.toString(args)

        MessageHandler handler = new MessageHandler(true);
        new Main().run(args, handler);
        for (IMessage message : handler.getMessages(null, true)) {
            switch (message.getKind()) {
                case IMessage.ABORT:
                case IMessage.ERROR:
                case IMessage.FAIL:
                    log.error message.message, message.thrown
                    break;
                case IMessage.WARNING:
                    log.warn message.message, message.thrown
                    break;
                case IMessage.INFO:
                    log.info message.message, message.thrown
                    break;
                case IMessage.DEBUG:
                    log.debug message.message, message.thrown
                    break;
            }
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.0'
    //需要添加
    compile files('libs/aspectjrt.jar')
    implementation files('libs/aspectjrt.jar')
}

  • 在module的libs目录下导入aspectj.jar 文件

    《小试牛刀--Android AOP(面向切面编程)开发》 image

创建注解类



@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface BehaviorTimeTrace {
    String value();
}

添加标记点(在需要处理的方法使用驻点)

  • 使用注解前的代码
/**
     * 语音的模块
     *
     * @param view
     */
    public  void shake(View view)
    {
        long beagin=System.currentTimeMillis();

        //摇一摇的代码逻辑
        
        SystemClock.sleep(3000);
        Log.i(TAG,"摇到一个妹子,距离500公里");
       

        Log.i(TAG,"消耗时间:  "+(System.currentTimeMillis()-beagin)+"ms");
    }

   /**
     * 摇一摇的模块
     *
     * @param view
     */
  @BehaviorTimeTrace("摇一摇")
    public void shake(View view){
        SystemClock.sleep(3000);
        Log.i(TAG,"摇到一个妹子,距离500公里");
    }

AOP处理

具体处理思想分为下面几步:

  • 1.获取标记点(获取我们注解的方法)
  • 2.处理注解

详细实现:

  • 创建类加上@Aspect注解,创建切面类
    此次类所有处理代码如下
@Aspect
public class BehaviorTimeAspect {
    SimpleDateFormat format =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static  final String TAG="AOPDemo";
    //比作切蛋糕,如何切蛋糕
    //第一步获切点,即获得想要处理方法:* *代表所有方法,(..)代表所有参数,这里可以根据具体的方法类型来做处理
//    @Pointcut("execution(@com.siqiyan.lightlu.aoptest.BehaviorTimeTrace  * *(..))")
    @Pointcut("execution(@com.siqiyan.lightlu.aoptest.BehaviorTimeTrace  * *(..))")
    public void insertBehavior(){

    }

     //对于想好切的蛋糕,如何吃
    //第二步处理获取的切点
    @Around("insertBehavior()")
    public Object dealPoint(ProceedingJoinPoint proceedingJoinPoint)throws Throwable{
        MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
        //获取标记的方法
        BehaviorTimeTrace annotation = signature.getMethod().getAnnotation(BehaviorTimeTrace.class);
        //获取标记方法名
        String value = annotation.value();

        Log.i(TAG,value+"开始使用的时间:   "+format.format(new Date()));
        long beagin=System.currentTimeMillis();
        Object proceed=null;

        try {
            //执行方法
            proceed = proceedingJoinPoint.proceed();
        }catch (Exception e){

        }
        Log.i(TAG,"消耗时间:  "+(System.currentTimeMillis()-beagin)+"ms");

        return proceed;

    }


}
  • 获取标记点处理
    这个方法用来处理,到根据注解类找到相应的方法:获得想要处理方法: * *代表所有方法,(..)代表所有参数,这里可以根据具体的方法类型来做处理
@Pointcut("execution(@com.siqiyan.lightlu.aoptest.BehaviorTimeTrace  * *(..))")
    public void insertBehavior(){

    }
  • 处理标记点
//关联上面的方法
  @Around("insertBehavior()")
    public Object dealPoint(ProceedingJoinPoint proceedingJoinPoint)throws Throwable{
    //固定写法,用于获取标记点
        MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
        //获取标记的方法
        BehaviorTimeTrace annotation = signature.getMethod().getAnnotation(BehaviorTimeTrace.class);
        //获取标记方法名,即我们注解传的参数
        String value = annotation.value();

        Log.i(TAG,value+"开始使用的时间:   "+format.format(new Date()));
        long beagin=System.currentTimeMillis();
        Object proceed=null;

        try {
            //执行我们注解的方法
            proceed = proceedingJoinPoint.proceed();
        }catch (Exception e){

        }
        Log.i(TAG,"消耗时间:  "+(System.currentTimeMillis()-beagin)+"ms");

        return proceed;

    }

效率

测试如下:

《小试牛刀--Android AOP(面向切面编程)开发》 image

可以看到使用AspectJ 框架编译时生成的字节码,所以处理逻辑会占用更少的时间。查看编译的源码我们可以看到生成的class文件里面包含注解的处理。

Demo源码

源码 AOPTest

    原文作者:鲁大先生
    原文地址: https://www.jianshu.com/p/d87fa9e306be
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞