1. 什么是AOP
与OOP对比,AOP是处理一些横切性问题,这些横切性问题不会影响到主逻辑实现的,但是会散落到代码的各个部分,难以维护。
AOP就是把这些问题和主业务逻辑分开,达到与主业务逻辑解耦的目的。
2. AOP的应用场景
- 日志记录
- 权限验证
- 效率检查
- 事务管理
3. Spring AOP原理及其应用
3.1 AOP相关概念
-
Aspect(切面): 通常是一个类(交给Spring容器管理),里面可以定义切入点和通知
-
JointPoint(连接点): 程序执行过程中的一个点,如方法的执行或异常的处理
-
Advice(通知): AOP在特定的切入点上执行的增强处理
-
通知类型:
- Before advice
- After returning advice
- After throwing advice
- After (finally) advice
- Around advice
调用顺序:
Around advice>Before advice>After (finally) advice>After returning advice/After throwing advice
-
Pointcut(切入点): 连接点的集合
-
Target object(目标对象):被通知对象
-
AOP proxy:AOP框架创建的对象,代理就是目标对象的增强。
- JDK dynamic proxy
- CGLIB proxy
思考: 初始化时织入还是获取对象时织入?
-
Weaving(织入):把代理逻辑加入到目标对象上的过程叫做织入
3.2 AOP的应用
3.2.1 Spring AOP with AspectJ pointcuts
Schema-based AOP Support
xml配置对AOP支持的 后置处理器
AspectJAwareAdvisorAutoProxyCreator
AnnotationAwareAspectJAutoProxyCreator // 配置 <aop:aspectj-autoproxy/>
spring-aop.xml
<!-- 自动为spring容器中那些配置@AspectJ切面的bean创建代理,织入切面
proxy-target-class默认为false,表示使用jdk动态代理织入增强,
当配为true时,表示使用Cglib动态代理技术织入增强-->
<aop:aspectj-autoproxy proxy-target-class="true"/>
<aop:config>
<!-- 配置切面-->
<aop:aspect id="myAspect" ref="xmlAspect">
<!-- 配置切入点-->
<aop:pointcut id="businessService"
expression="execution(* bat.ke.qq.com.dao.*.*(..))"/>
<!-- 通知-->
<aop:before pointcut-ref="businessService" method="before"/>
<aop:after pointcut-ref="businessService" method="after"/>
</aop:aspect>
</aop:config>
<bean id="xmlAspect" class="bat.ke.qq.com.config.XmlAspect"/>
<bean id="foxDao" class="bat.ke.qq.com.dao.FoxDao"/>
public class XmlAspect {
public void before(JoinPoint point) {
System.out.println("be