Spring AOP 各术语之间的联系

一.前置知识

​ AOP包含的几个术语有Aspect,Join point,Advice,Pointcut,Introduction,Target object,AOP proxy,Weaving。

在了解这几个术语之前,首先要知道Concern,Separation of concerns和Crosscutting Concern

  • concern(关注点):A Concern is a term that refers to a part of the system divided on the basis of the functionality.

​ 简单的来说,关注点就是你所关注的功能(模块),比如支付模块

  • Separation of concerns(关注点分离):Usually the code can be separated into logical sections, each addressing separate concerns, and so it hides the need for a given section to know particular information addressed by a different section.

    将代码分成单独的部分,即可以理解为不可再分割的组件,如日志组件和支付组件;

  • Crosscutting Concern(横切关注点):The crosscutting concern is a concern which is applicable throughout the application and it affects the entire application.

    For example: logging, security and data transfer are the concerns which are needed in almost every module of an application, hence they are cross-cutting concerns.

    一个影响很多模块或者所有模块的关注点。

二.术语介绍

下面以表格的方式,来对他们进行总结:

英文名 中文名 作用
Jointpoint 连接点 程序执行过程中的一个点,表示需要在程序中插入横切关注点的扩展点,例如方法的执行或异常的处理。在 Spring AOP 中,一个连接点总是代表一个方法执行。
Pointcut 切入点 选择一组相关连接点的模式,即可以认为连接点的集合。
Advice 通知 在连接点上执行的行为
Aspect 方面/切面 跨多个类的关注点的模块化(即横切关注点的模块化),比如日志组件
Introduction
(inter-type declaration)
引入 也称为内部类型声明,为已有的类添加额外新的字段或方法,Spring允许引入新的接口(必须对应一个实现)到所有被代理对象(目标对象)
Target Object 目标对象 需要被织入横切关注点的对象,即该对象是切入点选择的对象,需要被通知的对象,从而也可称为“被通知对象”;由于Spring AOP 通过代理模式实现,从而这个对象永远是被代理对象
AOP Proxy Object AOP代理对象 AOP框架使用代理模式创建的对象,从而实现在连接点处插入通知(即应用切面),就是通过代理来对目标对象应用切面。在Spring中,AOP代理可以用JDK动态代理或CGLIB代理实现,而通过拦截器模型应用切面。
Weaving 织入 织入是一个过程,是将切面应用到目标对象从而创建出AOP代理对象的过程,织入可以在编译期、类装载期、运行期进行。

在AOP中,通过切入点选择目标对象的连接点,然后在目标对象的相应连接点处织入通知,而切入点和通知就是切面(横切关注点),而在目标对象连接点处应用切面的实现方式是通过AOP代理对象,如图所示

这是曾经写过的一个AOP例子:

1
2
3
4
5
6
7
8
9
10
11
12
@AfterReturning(value = "execution(* *..service.Impl.group.GroupInfoServiceImpl.createGroup(..))",returning = "result")
public void createGroupInfo(JoinPoint jp,boolean result){
if(result==true){
Object[] args = jp.getArgs();
GroupInfo groupInfo=(GroupInfo) args[0];
Long userId=(Long) args[1];
String username = dataAopDao.getName(userId);
String operation="组建了\""+groupInfo.getGroupName()+"\"队伍";
DataInfo dataInfo=new DataInfo(username,operation,1);
dataInfoDao.insert(dataInfo);
}
}

参考:https://wizardforcel.gitbooks.io/gen-wo-xue-spring/content/36.html

https://stackoverflow.com/questions/23700540/cross-cutting-concern-example

https://en.wikipedia.org/wiki/Concern_(computer_science)

https://en.wikipedia.org/wiki/Separation_of_concerns

https://en.wikipedia.org/wiki/Cross-cutting_concern