AOP 是 Aspect Oriented Programming 的缩写,
切面编程
什么是 AOP
AOP 中的概念:
- Aspect 切面类,管理切点,通知等
- Join point,连接点,在Spring AOP,Join point 代表一个方法的执行,代表增强的方法
- Advice: 通知, action taken by an aspect at a particular join point.Different types of advice include “around”, “before” and “after” advice.
- Pointcut: 切点,a predicate that matches join points. Advice is associated with a pointcut expression and runs at any join point matched by the pointcut (for example, the execution of a method with a certain name). The concept of join points as matched by pointcut expressions is central to AOP, and Spring uses the AspectJ pointcut expression language by default.
- Target object: 目标对象,object being advised by one or more aspects. Also referred to as the advised object. Since Spring AOP is implemented using runtime proxies, this object will always be a proxied object.
- AOP proxy: an object created by the AOP framework in order to implement the aspect contracts (advise method executions and so on). In the Spring Framework, an AOP proxy will be a JDK dynamic proxy or a CGLIB proxy.
- Weaving: linking aspects with other application types or objects to create an advised object. This can be done at compile time (using the AspectJ compiler, for example), load time, or at runtime. Spring AOP, like other pure Java AOP frameworks, performs weaving at runtime.
- Introduction: declaring additional methods or fields on behalf of a type. Spring AOP allows you to introduce new interfaces (and a corresponding implementation) to any advised object. For example, you could use an introduction to make a bean implement an IsModified interface, to simplify caching. (An introduction is known as an inter-type declaration in the AspectJ community.)
切面 Aspect
切面,指切面类,管理切点和通知。
面向切面编程。
切点 Pointcut
定义需要增强到那些方法中。配合切点表达式。
通知 Advice
增强到业务代码中的公共代码,有很多类型,在不同位置,前置通知,后置通知,异常通知,返回通知,环绕通知
Target 目标对象
被增强的对象。
Weaving
AspectJ 中独有的关键字。
Spring AOP 织入方式,就是动态代理。AspectJ 中会存在不同的方式,编译器,类加载器,运行期。
为什么要使用 AOP
- 减少代码冗余,解耦
- 抽象共同的逻辑,日志,事务,权限
- Spring AOP 基于动态代理,JDK 动态代理,CGLib 代理
Spring AOP 属于运行时增强,而 AspectJ 是编译时增强。
- Spring AOP 基于代理
- 而 AspectJ 基于字节码操作(Bytecode Manipulation)。