理解AOP之”深究“
在前两篇文章里,从浅层面定义了一下什么是AOP和AOP的基本实现原理。但是真正在使用AOP的时候还是比较复杂的,首先需要了解一下AOP的一些术语。
Aspect:切面,应用中多个类(方法)的共同关注点,例如事务管理,错误日志,缓存等。Join Point:连接点,一个连接点是应用程序中的一个特定的时机或者说是切面介入的时机,例如方法执行、异常处理、改变对象变量的值等等。Pointcut:切入点,切入点是一些表达式,当匹配到连接点时决定通知是否需要执行。可以这样理解,方法的执行是一个连接点,但是如果我们不希望所有的方法都被切面涉入,我们可以通过切入点表达式过滤出我们不需要的那些方法。Advice:通知,通知是指在一个特别的连接点上发生的动作。类似于事件回调。通知一般分为:
-
Before Advice:前置通知,在连接点方法执行之前运行。After (finally) Advice:后置通知,在连接点方法执行完成之后运行。After Returning Advice:后置返回通知,在方法返回之后运行。After Throwing Advice:异常通知,在方法抛出异常之后运行。Around Advice:环绕通知,这个通知在连接点方法前后运行并且我们可以决定该通知是否运行。
Target Object:通知执行的目标对象。是一个被代理的对象。AOP proxy:Target Object的代理wrapper。Weaving:织入,将切面和其他用于创建被通知的代理对象的类联系起来的过程。这可以是在运行时完成,也可以是在代码加载过程中或者运行时。
相信很多人会对Joinpoint和Pointcut会感觉有点混淆,开始的时候我也一样。不过在stackoverflow上看到了一个回复,是这这样描述这两者的差别的:
When you go out to a restaurant, you look at a menu and see several options to choose from. You can order one or more of any of the items on the menu. But until you actually order them, they are just "opportunities to dine". Once you place the order and the waiter brings it to your table, it's a meal.
Join points are the options on the menu and pointcuts are the items you select. A joinpoint is an opportunity within code for you to apply an aspect...just an opportunity. Once you take that opportunity and select one or more joinpoints and apply an aspect to them, you've got a pointcut.
所以说Joinpoint定义了Aspect介入的时机,例如方法的执行(对于Spring而言,这是唯一的选项)。那么如果没有Pointcut,所有的方法在执行时都会引起Aspect的介入。通过Pointcut我们可以通过切入点表达式筛选我们需要Aspect介入的方法。
浙公网安备 33010602011771号