如需轉(zhuǎn)載請?jiān)u論或簡信截碴,并注明出處呀伙,未經(jīng)允許不得轉(zhuǎn)載
目錄
前言
AspectJ是一個(gè)面向切面的框架你稚,它擴(kuò)展了Java語言。AspectJ定義了AOP語法醒颖,它有一個(gè)專門的編譯器(ajc)用來生成遵守Java字節(jié)編碼規(guī)范的Class文件
有關(guān)AOP的概念不是很清楚的可以看:http://www.reibang.com/p/c40528c8df17
為什么要使用AspectJ
在使用Aspectj之前妻怎,先來看下面這么一個(gè)例子,以便于我們理解我們?yōu)槭裁匆褂盟?/p>
最近項(xiàng)目在做性能優(yōu)化泞歉,需要統(tǒng)計(jì)一些方法的的耗時(shí)逼侦,那我們一般會這么去做
public void parserHtml() {
long currentTimeMillis = System.currentTimeMillis();
//下面省略解析html的業(yè)務(wù)代碼
.........
long time = System.currentTimeMillis() - currentTimeMillis;
System.out.println("parserHtml方法耗時(shí):" + time + "ms");
}
但是如果我們有很多方法都需要做耗時(shí)統(tǒng)計(jì)呢,如果這些統(tǒng)計(jì)策略隨著產(chǎn)品需求所改變呢腰耙。難道我們需要在每個(gè)方法中的前后都手動編寫這樣的統(tǒng)計(jì)代碼榛丢?這樣的寫法不僅會產(chǎn)生代碼的重復(fù),同時(shí)也給代碼的維護(hù)工作造成了麻煩挺庞。所以這時(shí)候我們就要用到AOP這種面向切面編程的思想來進(jìn)行程序設(shè)計(jì)
AspectJ提供了相應(yīng)的方法晰赞,可以幫助我們方便快捷的在編譯期對方法前后進(jìn)行代碼插樁,從而實(shí)現(xiàn)業(yè)務(wù)需求和功能需求的解耦
AspectJ集成步驟
在實(shí)際項(xiàng)目中选侨,我們往往會把AspectJ相關(guān)的代碼單獨(dú)放到一個(gè)module中
- 新建android module命名為aspectj
- 在aspectJ module中添加jar包依賴
repositories {
mavenCentral()
}
dependencies {
api 'org.aspectj:aspectjrt:1.8.9'
}
- 在aspectJ module中添加classpath依賴
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'org.aspectj:aspectjtools:1.8.9'
}
}
- 在aspectJ module中添加gradle執(zhí)行腳本
import org.aspectj.bridge.IMessage
import org.aspectj.bridge.MessageHandler
import org.aspectj.tools.ajc.Main
android.libraryVariants.all { variant ->
JavaCompile javaCompile = variant.javaCompile
javaCompile.doLast {
String[] args = ["-showWeaveInfo",
"-1.5",
"-inpath", javaCompile.destinationDir.toString(),
"-aspectpath", javaCompile.classpath.asPath,
"-d", javaCompile.destinationDir.toString(),
"-classpath", javaCompile.classpath.asPath,
"-bootclasspath", project.android.bootClasspath.join(File.pathSeparator)
]
MessageHandler handler = new MessageHandler(true);
new Main().run(args, handler)
def log = project.logger
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:
case IMessage.INFO:
log.info message.message, message.thrown
break;
case IMessage.DEBUG:
log.debug message.message, message.thrown
break;
}
}
}
}
- 在app module中添加aspect module依賴
dependencies {
api project(':aspectj')
}
- 同樣需要在app module下添加classpath依賴和gradle執(zhí)行腳本
gradle配置參考文章:Aspect Oriented Programming in Android
AspectJ初體驗(yàn)
我們現(xiàn)在使用AspectJ來實(shí)現(xiàn)我們上面說到的方法統(tǒng)計(jì)
- 新建一個(gè)注解類BehaviorTrace
這是一個(gè)運(yùn)行時(shí)注解掖鱼。雖然我們在編譯期間就完成了代碼的注入,但是我們將我們的注解保留到運(yùn)行時(shí)援制,以便于獲取注解中的value
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface BehaviorTrace {
String value();
}
- 在需要統(tǒng)計(jì)耗時(shí)的方法上加上BehaviorTrace注解
@BehaviorTrace("搖一搖")
public void shake(View btn) {
Log.i(TAG, "搖一搖...");
//模擬執(zhí)行耗費(fèi)時(shí)間的代碼
SystemClock.sleep(20);
}
- 編寫切面類
我們先嘗試跟著注釋理解一下代碼戏挡,稍后還會做更詳細(xì)地介紹
@Aspect
public class BehaviorAspect {
private static final String POINTCUT_METHOD =
"execution(@com.geekholt.aspectj.annotation.BehaviorTrace * *(..))";
//任何一個(gè)包下面的任何一個(gè)類下面的任何一個(gè)帶有BehaviorTrace的方法,構(gòu)成了這個(gè)切面
@Pointcut(POINTCUT_METHOD)
public void annoHaviorTrace() {
Log.i("geekholt", "annoHaviorTrace");
}
//攔截方法
@Around("annoHaviorTrace()")
public Object weaveJoinPoint(ProceedingJoinPoint joinPoint) throws Throwable {
Log.i("", "weaveJoinPoint");
//拿到方法的簽名
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
//類名
String className = methodSignature.getDeclaringType().getSimpleName();
//方法名
String methodName = methodSignature.getName();
//功能名
BehaviorTrace behaviorTrace = methodSignature.getMethod().getAnnotation(BehaviorTrace.class);
String fun = behaviorTrace.value();
//方法執(zhí)行前
long begin = System.currentTimeMillis();
//執(zhí)行攔截方法
Object result = joinPoint.proceed();
//方法執(zhí)行后
long duration = System.currentTimeMillis() - begin;
Log.i("geekholt", String.format("功能:%s晨仑,%s的%s方法執(zhí)行褐墅,耗時(shí):%d ms", fun, className, methodName, duration));
return result;
}
}
- 運(yùn)行程序
我們只在shake
方法上加上了注解,并沒有在方法中添加其他代碼洪己,但是卻完成了方法耗時(shí)統(tǒng)計(jì)妥凳。如果還有別的方法需要進(jìn)行統(tǒng)計(jì),我們同樣只需要在方法上加上注解就可以了
使用AspectJ實(shí)現(xiàn)方法統(tǒng)計(jì)不僅代碼優(yōu)雅码泛,侵入性非常低猾封,還可以將業(yè)務(wù)代碼和相關(guān)功能代碼在不同的模塊中進(jìn)行管理
- 查看build? /?intermediates?/javac目錄下的文件
可以看出澄耍,aspectJ會在編譯時(shí)幫我們在shake
方法中插入一些代碼
@BehaviorTrace("搖一搖")
public void shake(View btn) {
JoinPoint var3 = Factory.makeJP(ajc$tjp_0, this, this, btn);
BehaviorAspect var10000 = BehaviorAspect.aspectOf();
Object[] var4 = new Object[]{this, btn, var3};
var10000.weaveJoinPoint((new MainActivity$AjcClosure1(var4)).linkClosureAndJoinPoint(69648));
}
AspectJ詳解
相關(guān)注解介紹
- @Aspect:聲明切面噪珊,標(biāo)記類
- @Pointcut(切點(diǎn)表達(dá)式):定義切點(diǎn),標(biāo)記方法
- @Before(切點(diǎn)表達(dá)式):前置通知齐莲,切點(diǎn)之前執(zhí)行
- @Around(切點(diǎn)表達(dá)式):環(huán)繞通知痢站,切點(diǎn)前后執(zhí)行
- @After(切點(diǎn)表達(dá)式):后置通知,切點(diǎn)之后執(zhí)行
- @AfterReturning(切點(diǎn)表達(dá)式):返回通知选酗,切點(diǎn)方法返回結(jié)果之后執(zhí)行
- @AfterThrowing(切點(diǎn)表達(dá)式):異常通知阵难,切點(diǎn)拋出異常時(shí)執(zhí)行
@Pointcut、@Before芒填、@Around呜叫、@After空繁、@AfterReturning、@AfterThrowing需要在切面類中使用朱庆,即標(biāo)注了@Aspect的類中
切點(diǎn)表達(dá)式
切點(diǎn)表達(dá)式的組成如下:
除了返回類型模式盛泡、方法名模式和參數(shù)模式外,其它項(xiàng)都是可選的娱颊。修飾符模式指的是public傲诵、private、protected箱硕,異常模式指的是NullPointException等
execution(<修飾符模式>? <返回類型模式> <方法名模式>(<參數(shù)模式>) <異常模式>?)
下面列出幾個(gè)例子說明一下
- 匹配所有public方法拴竹,在方法執(zhí)行之前打印"Geekholt"
@Before("execution(public * *(..))")
public void before(JoinPoint point) {
System.out.println("Geekholt");
}
- 匹配所有以"to"結(jié)尾的方法,在方法執(zhí)行之前打印"Geek"剧罩,在方法執(zhí)行之后打印"holt"
@Around("execution(* *to(..))")
public void around(ProceedingJoinPoint joinPoint) {
System.out.println("Geek");
joinPoint.proceed();
System.out.println("holt");
}
- 匹配com.geekholt包下及其子包中以"to"結(jié)尾的方法栓拜,在方法執(zhí)行之后打印"Geekholt"
@After("execution(* com.geekholt..*to(..))")
public void after(JoinPoint point) {
System.out.println("Geekholt");
}
- 匹配com.geekholt包下所有返回類型是int的方法,在方法返回結(jié)果之后打印"Geekholt"
@AfterReturning("execution(int com.geekholt.*(..))")
public void afterReturning(JoinPoint point, Object returnValue) {
System.out.println("Geekholt");
}
- 匹配com.geekholt包及其子包中的所有方法斑响,當(dāng)方法拋出異常時(shí)菱属,打印"ex = 報(bào)錯(cuò)信息"
@AfterThrowing(value = "execution(* com.geekholt..*(..))", throwing = "ex")
public void afterThrowing(Throwable ex) {
System.out.println("ex = " + ex.getMessage());
}
@Pointcut的使用
@Pointcut
是專門用來定義切點(diǎn)的,讓切點(diǎn)表達(dá)式可以復(fù)用
你可能需要在切點(diǎn)執(zhí)行之前和切點(diǎn)報(bào)出異常時(shí)做些動作(如:出錯(cuò)時(shí)記錄日志)舰罚,可以這么做:
@Before("execution(* com.geekholt..*(..))")
public void before(JoinPoint point) {
System.out.println("Geekholt");
}
@AfterThrowing(value = "execution(* com.geekholt..*(..))", throwing = "ex")
public void afterThrowing(Throwable ex) {
System.out.println("記錄日志");
}
可以看到纽门,表達(dá)式是一樣的,那要怎么重用這個(gè)表達(dá)式呢营罢?這就需要用到@Pointcut
注解了赏陵,@Pointcut
注解是注解在一個(gè)空方法上的,如:
@Pointcut("execution(* com.geekholt..*(..))")
public void pointcut() {}
這時(shí)饲漾,pointcut()
就等價(jià)于execution(* com.geekholt..*(..))
蝙搔,那么上面的代碼就可以改成這樣
@Pointcut("execution(* com.geekholt..*(..))")
public void pointcut() {}
@Before("pointcut()")
public void before(JoinPoint point) {
System.out.println("Geekholt");
}
@AfterThrowing(value = "pointcut()", throwing = "ex")
public void afterThrowing(Throwable ex) {
System.out.println("記錄日志");
}
Kotlin中使用AspectJ
雖然是kotlin和java之間可以互相調(diào)用,但是想要在kotlin中直接使用aspectJ是不會有效果的考传,這里推薦一個(gè)大神寫的框架aspectjx吃型,很好的支持了Kotlin,具體的使用直接看github上的文檔,這里就不過多介紹啦
總結(jié)
AspectJ在Android中還可以做很多事情,比如無埋點(diǎn)旋廷、參數(shù)校驗(yàn)和判空锚烦、Android API23+權(quán)限控制、事件防抖、異常處理、緩存等等
學(xué)習(xí)AspectJ重要的是理解AOP的思想,在合適的場景下使用AOP挺邀,通過正確的切點(diǎn)表達(dá)式找準(zhǔn)切入點(diǎn)