一、引言
自定义Pointcuts
自定义Pointcuts可以让我们更加精确的切入一个或多个指定的切入点。其具体操作步骤如下:
1.首先,我们需要自定义一个注解类
@Retention(RetentionPolicy.CLASS)
@Target({ElementType.CONSTRUCTOR,ElementType.METHOD})
public @interface AopLog {}
2.然后,创建一个切面文件,内部通过一个Pointcut来指定在带有我们上面自定义注解类AopLog注解的所有方法上进行拦截。
下面两种方式都可以实现切面定义
@Aspect
public class AopLogPointcut {
//在带有AopLog注解的方法进行切入(注:此处的 * *前面都要有一个空格)
@Pointcut("execution(@com.yn.aspectj.selfmakeaop.AopLog * *(..))")
public void logPointcut(){} //注意,这个函数必须要有实现,否则Java编译器会报错
@After("logPointcut()")
public void onLogPointcutAfter(JoinPoint joinPoint) throws Throwable{
Log.i("AOP","onLogPointcutAfter:"+joinPoint.getSignature());
}
}
@Aspect
public class AopLogPointcut {
//在带有AopLog注解的方法进行切入(注:此处的 * *前面都要有一个空格)
@After("execution(@com.yn.aspectj.selfmakeaop.AopLog * *(..))")
public void onLogPointcutAfter(JoinPoint joinPoint) throws Throwable{
Log.i("AOP","onLogPointcutAfter:"+joinPoint.getSignature());
}
}
3.最后,只需要在要进行切入的函数前加上@AopLog注解即可。
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
testAopLog();
}
@AopLog
public void testAopLog() {
Log.i("AOP","in testAopLog");
}
}
掌握上述方法,则AOP基本编程便可以使用了。
作者:Whyn
链接:https://www.jianshu.com/p/e94cdbe67a84
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
https://blog.csdn.net/github_34889651/article/details/51321499