小試牛刀--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 文件
    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;

    }

效率

測試如下:
image

可以看到使用AspectJ 框架編譯時生成的字節碼,所以處理邏輯會佔用更少的時間。查看編譯的源碼我們可以看到生成的class文件裏面包含註解的處理。

Demo源碼

源碼 AOPTest

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章