AOP在Android中的应用

官网地址:https://fernandocejas.com/2014/08/03/aspect-oriented-programming-in-android/


OOP

(面向对象编程)针对业务处理过程的实体及其属性和行为进行抽象封装,以获得更加清晰高效的逻辑单元划分。


AOP

 (面向切面变成)针对业务处理过程中的切面进行提取,它所面对的是    处理过程中的某个步骤或阶段,以获得逻辑过程中各部分之间低耦合性的隔离效果。

   

这两种设计思想在目标上有着本质的差异。



AOP是对OOP的补充,不是替代。


几个概念(来自http://blog.csdn.net/a1314517love/article/details/11847087)

1. Cross Cutting Concern:是一种独立服务,它会遍布在系统的处理流程之中
2. Aspect 对横切行关注点的模块化
3. Advice对横切行关注点的具体实现(有分类的概念,之前,之后,throw)
4. Pointcut 它定义了Advice应用到哪些JoinPoint上,对spring来说是方法调用
5. Weave 将Advice应用target Object上的过程叫织入,Spring支持的是动态织入
6. Target Object  Advice被应用的对象
7. Proxy:Spring AOP默认使用JDK的动态代理,它的代理是运行时创建,也可以使用CGLIB代理
8.Introduction 可以动态的为类添加方法   
9.JoinPoint:Advice在应用程序上执行的点或时机,Spring只支持方法的JointPoint
这些概念听上去还是比较抽象的,下面我们通过AOP的原理图和实例来具体看一下这些概念具体指的是什么。



下面同过demo来演示AOP的使用:

github上有篇文章介绍的挺详细:https://github.com/hehonghui/android-tech-frontier/blob/master/issue-22/Android%E4%B8%AD%E7%9A%84AOP%E7%BC%96%E7%A8%8B.md

 AOP涉及到反射和注解的知识

反射:http://blog.csdn.net/whitepony/article/details/23096845

注解:http://blog.csdn.net/whitepony/article/details/23099541


关于AOP 中execution

内容来源:http://www.it610.com/article/256837.htm

表示com.xy.service包下的所有方法为为事务管理。

 

execution(* com.aptech.jb.epet.dao.hibimpl.*.*(..)) 

 

这样写应该就可以了 这是com.aptech.jb.epet.dao.hibimpl 包下所有的类的所有方法。。

第一个*代表所有的返回值类型 

第二个*代表所有的类

第三个*代表类所有方法 最后一个..代表所有的参数。

 

 

下面给出一些常见切入点表达式的例子:

任意公共方法的执行:

execution(public * *(..))

任何一个以“set”开始的方法的执行:

execution(* set*(..))

AccountService 接口的任意方法的执行:

execution(* com.xyz.service.AccountService.*(..))

定义在service包里的任意方法的执行:

execution(* com.xyz.service.*.*(..))

定义在service包或者子包里的任意类的任意方法的执行:

execution(* com.xyz.service..*.*(..))



下面分两个小Demo,一个直接应用在Android项目中,一个座位Android Library使用


Android项目:


项目结构



需要使用的aspectjrt.jar包,源码同官网(build.gradle文件的配置需要注意)


MainActivity.java类

package cn.edu.sxu.www.aopdemo;

import android.os.Bundle;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private Button button;
    private Button button2;
    private String TAG="cn.edu.sxu.www.aopdemo.MainActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button= (Button) findViewById(R.id.button);
        button2= (Button) findViewById(R.id.button2);
        button.setOnClickListener(this);
        button2.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {

        switch (view.getId())
        {
            case R.id.button:
                commonTest();
                break;
            case R.id.button2:
                aopTest();
                break;
        }

    }

    /**
     * 普通统计
     */

    private void  commonTest()
    {
        final StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        SystemClock.sleep(2000);
        stopWatch.stop();

        DebugLog.log(TAG, "所用时长:"+stopWatch.getTotalTimeMillis());

    }

    /**
     * aop 统计
     */
    @DebugTrace
    private void aopTest()
    {
        SystemClock.sleep(3000);
    }
}


DebugTrace.java 类

package cn.edu.sxu.www.aopdemo;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.CLASS)
@Target({ ElementType.CONSTRUCTOR, ElementType.METHOD })
public @interface DebugTrace {}


TraceAspect.java类

package cn.edu.sxu.www.aopdemo;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;

/**
 * Aspect representing the cross cutting-concern: Method and Constructor Tracing.
 */
@Aspect
public class TraceAspect {

  private static final String POINTCUT_METHOD =
      "execution(@cn.edu.sxu.www.aopdemo.DebugTrace * *(..))";

  private static final String POINTCUT_CONSTRUCTOR =
      "execution(@cn.edu.sxu.www.aopdemo *.new(..))";

  @Pointcut(POINTCUT_METHOD)
  public void methodAnnotatedWithDebugTrace() {}

  @Pointcut(POINTCUT_CONSTRUCTOR)
  public void constructorAnnotatedDebugTrace() {}

  @Around("methodAnnotatedWithDebugTrace() || constructorAnnotatedDebugTrace()")
  public Object weaveJoinPoint(ProceedingJoinPoint joinPoint) throws Throwable {
    MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
    String className = methodSignature.getDeclaringType().getSimpleName();
    String methodName = methodSignature.getName();

    final StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    Object result = joinPoint.proceed();
    stopWatch.stop();

    DebugLog.log(className, buildLogMessage(methodName, stopWatch.getTotalTimeMillis()));

    return result;
  }

  /**
   * Create a log message.
   *
   * @param methodName A string with the method name.
   * @param methodDuration Duration of the method in milliseconds.
   * @return A string representing message.
   */
  private static String buildLogMessage(String methodName, long methodDuration) {
    StringBuilder message = new StringBuilder();
    message.append("Gintonic --> ");
    message.append(methodName);
    message.append(" --> ");
    message.append("[");
    message.append(methodDuration);
    message.append("ms");
    message.append("]");

    return message.toString();
  }
}

StopWatch.java类

package cn.edu.sxu.www.aopdemo;

import java.util.concurrent.TimeUnit;

/**
 * Class representing a StopWatch for measuring time.
 */
public class StopWatch {
  private long startTime;
  private long endTime;
  private long elapsedTime;

  public StopWatch() {
    //empty
  }

  private void reset() {
    startTime = 0;
    endTime = 0;
    elapsedTime = 0;
  }

  public void start() {
    reset();
    startTime = System.nanoTime();
  }

  public void stop() {
    if (startTime != 0) {
      endTime = System.nanoTime();
      elapsedTime = endTime - startTime;
    } else {
      reset();
    }
  }

  public long getTotalTimeMillis() {
    return (elapsedTime != 0) ? TimeUnit.NANOSECONDS.toMillis(endTime - startTime) : 0;
  }
}


DebugLog.java类

package cn.edu.sxu.www.aopdemo;

import android.util.Log;

/**
 * Wrapper around {@link android.util.Log}
 */
public class DebugLog {

  private DebugLog() {}

  /**
   * Send a debug log message
   *
   * @param tag Source of a log message.
   * @param message The message you would like logged.
   */
  public static void log(String tag, String message) {
    Log.d(tag, message);
  }
}


activity_main.xml文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="cn.edu.sxu.www.aopdemo.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="官网demo,统计方法运行时间"
        android:id="@+id/textView" />

    <Button
        android:text="普通方式"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="42dp"
        android:id="@+id/button" />

    <Button
        android:text="aop方式"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button"
        android:layout_alignRight="@+id/button"
        android:layout_alignEnd="@+id/button"
        android:layout_marginTop="87dp"
        android:id="@+id/button2" />
</RelativeLayout>


build.gradle文件


apply plugin: 'com.android.application'

import org.aspectj.bridge.IMessage
import org.aspectj.bridge.MessageHandler
import org.aspectj.tools.ajc.Main
buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'org.aspectj:aspectjtools:1.8.9'
        classpath 'org.aspectj:aspectjweaver:1.8.9'
    }
}
android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "cn.edu.sxu.www.aopdemo"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    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 {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.1.0'
    testCompile 'junit:junit:4.12'
}


build.gradle文件的配置方式官网上有,只不过官网提供的是作为依赖库使用的


验证:




源码地址:http://download.csdn.net/detail/huohacker/9761873


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值