Android 面向切面编程-aspjectj应用

先附上自己基于aspject封装的aop 插件 

1.为什么要用切面

  随着业务越来越复杂,项目中的模块可能越来越多, 面向切面可以减少模块间的耦合,提高模块的复用率

2.aspjectj语法

android aop框架 有好几种,不过aspjectj应该算最成熟了,github上很多开源的也是基于这个框架的,先简单介绍下aspject语法

 

    @After("execution(* com.vapi.test.MyTest.get**(..))")
    public void onLibraryTestMethod(JoinPoint joinPoint) throws Throwable {
        Log.e("helloAOP", "mytestlibrary:::" + joinPoint.getSignature());
    }

  

从下面的join point 对应android 的代码可以看书, 主要是切面类型,普通方法或者构造器

point cut

call: 在织入方法处

execution: 在织入方法内

 这两个的区别很容易理解, 比如a.b(),  call是在a.b()前后, execution 在b()内

within和target 匹配制定类型 可以是注解类型

 

    @After("@within(com.lin.aopdemotest.anno.WithInMark)")
    public void onTestWith(JoinPoint joinPoint) throws Throwable {
        Log.e(TAG, "com.lin.aopdemotest.anno.WithInMark :::" );
    }

  

advice

after,before: 织入前后

afterReturn, afterThrows:织入方法会报错的时候

around: 可以理解为直接替换方法, 在方法内自行决定处理被调用方法

Pointcut: 声明一个切面,后面after,before可以直接引用声明的切面,相当于定义了一个引用

 

3. android 接入aspjectj

kotlin跟java编译后的路径是不一样的 需要单独处理 这里需要注意下, 

                String[] kotlinArgs = ["-showWeaveInfo",
                                       "-1.8",
                                       "-inpath", kotlinInPath,
                                       "-aspectpath", aspectpath,
                                       "-d", kotlinPath,
                                       "-classpath", totalPath,
                                       "-bootclasspath", project.android.bootClasspath.join(
                        File.pathSeparator)]
                MessageHandler handler = new MessageHandler(true)

  inpath: 需要切面的路径

      aspectpath: 切面包的路径 即 @Aspect的路径

      -d:  切面后新生成文件路径,一般等于inpath

    -classpath: 类库路径, 这里需要注意,需要被切面的包得先加入

具体代码可以看github 最上面的链接

posted @ 2019-04-03 17:48  dikeboyR  阅读(879)  评论(0编辑  收藏  举报