版权声明:本文为匆忙拥挤repeat(stone)原创文章,转载请注明出处 —— http://blog.csdn.net/jjwwmlp456 https://blog.csdn.net/jjwwmlp456/article/details/88877927
总结
- 在 app 中的配置与 library 中的配置是有点点不一样的。app中用
applicationVariants
library中用libraryVariants
- 在哪个 module 中进行aop 操作,就需要在那个 module 中进行配置。
- 不同的 module 无法相互进行 aop 操作。就是说 a-module,有个使用了@Aspect 的类要进行 aop 操作,但在 具体切点规则中需要找到其它 module中的类、方法、属性进行 aop 操作,是不行的。
环境:
aspectJ 1.9.+ 支持 java9
配置
root/build.gradle
buildscript {
...
def versions = [:]
ext.versions = versions
versions.aspectj = '1.9.3.RC1'
dependencies {
classpath "org.aspectj:aspectjrt:$versions.aspectj"
classpath "org.aspectj:aspectjrt:$versions.aspectj"
}
}
module/build.gradle
在需要 aop 操作的 module/build.gradle 中
比如在 app-module 中
apply plugin: 'com.android.application'
...
android { ... }
//aspectj start
import org.aspectj.bridge.IMessage
import org.aspectj.bridge.MessageHandler
import org.aspectj.tools.ajc.Main
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//警告:studio 3.3过时了
// def javaCompile = variant.getJavaCompileProvider()//还会引起其它异常
javaCompile.doLast {
String[] args = ["-showWeaveInfo",
"-1.9",
"-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
}
}
}
}
//aspectj end
dependencies { ... }
若是在 library-module 中,只需要将 applicationVariants
换成 libraryVariants
。
dependencies
在需要 aop 操作的 module/build.gradle 中,
implementation "org.aspectj:aspectjrt:$versions.aspectj"
依赖后,可以使用 AspectJ 中的注解