AspectJ简单使用
1.首先创建一个注解类,
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FUNCTION)
annotation class AopCommand
其中@Target(AnnotationTarget.FUNCTION)表示该注解只能用在方法上。
2.创建Aspect实现类,用来过滤和实现日志打印,@Aspect:声明切面,标记类,使用下面注解之前一定要在类使用@Aspec
@Aspect
class AopAspect{
@Pointcut("execution(@com.example.aopaspectj.log.AopCommand * *(..))") fun pointcut() {
}
@Around("pointcut()")
@Throws(Throwable::class)
fun AopAround(joinPoint: ProceedingJoinPoint) {
Log.d("zhuanghz", "-----先将强哥绑起来-----")
}
}
3.执行的方法
@AopCommand
fun luQiangGe() {
Log.d("zhuanghz", "-----撸强哥-----")
}
4.运行结果如下:
D/zhuanghz: -----先将强哥绑起来-----
阿勒,竟然没有打印撸强哥。
别急,我们再来看下around方法,这边我们只是打印了日志,没有了其他操作,此时我们如果需要返回原来的目标方法,就需要调用proceed(),切到目标方法里。这边我们重新修改成如下代码:
@Around("pointcut()")
@Throws(Throwable::class)
fun AopAround(joinPoint: ProceedingJoinPoint) {
Log.d("zhuanghz", "-----先将强哥绑起来-----")
joinPoint.proceed()
Log.d("zhuanghz", "-----撸完走人-----")
}
try again!
D/zhuanghz: -----先将强哥绑起来-----
D/zhuanghz: -----撸强哥-----
D/zhuanghz: -----撸完走人-----
强哥保佑,这次有了。
AspectJ Advice 的执行顺序
前面讲了AspectJ的集成和简单使用,接下来我们来了解下Advice的其他方法和执行顺序。
我们修改AopAspect类,在里面加入Advice其他的通知,先简单的加入几个通知的方法,代码如下:
@Before("pointcut()")
fun aopBefore() {
Log.d("zhuanghz", "-----Before-----")
}
@Around("pointcut()")
@Throws(Throwable::class)
fun aopAround(joinPoint: ProceedingJoinPoint) {
Log.d("zhuanghz", "-----Around 1-----")
joinPoint.proceed()
Log.d("zhuanghz", "-----Around 2-----")
}
@After("pointcut()")
fun aopAfter() {
Log.d("zhuanghz", "-----After-----")
}
@AfterReturning(pointcut="pointcut()")
fun aopReturning() {
Log.d("zhuanghz", "-----AfterReturning-----")
}
@AfterThrowing(pointcut = "pointcut()", throwing = "throwable")
fun aopThrowing(point:JoinPoint ,throwable: Throwable) {
Log.d("zhuanghz", "-----AfterThrowing-----")
}
-
这边可以看到,代码里面多了几个由@Before、@After、@AfterReturning、@AfterThrowing注解的方法。让我们看下输出日志
log.png -
发现相较于没有异常的情况,少打印Around 2 和 AfterReturning,多打印了AfterThrowing,同时程序发生了崩溃。
如果此时我们对异常代码块进行try-catch会怎样呢?
try.png-
此时运行的结果是:
logresult.png -
可以看到对异常代码进行try-catch之后,打印的日志和前面无异常的是一致的。只要切点方法没有出现异常,则不会执行Advice的@AfterThrowing。
本次先简单了解下AspectJ的基础使用,后续再继续深入学习AspectJ。
对于刚刚学aop注意几个坑
-
在切入表达式中,由于没有代码提示,因此不要写错了
-
使用@Pointcut来写切入点时注意是“方法名()”,不要遗漏了括号
-
@Around方法的参数要写对,是joinPoint: ProceedingJoinPoint
网友评论