
luckydog
V1
2022/04/18阅读:22主题:默认主题
Spring-AOP
Spring AOP
AOP介绍
1.面向切面编程,对业务逻辑的各个部分进行隔离,解耦合
AOP底层原理
底层使用动态代理
1.有接口的情况,使用JDk动态代理
创建接口实现类代理对象
-->使用Java.lang包下的Proxy类的newProxyInstance方法

ClassLoader loader: 代理类的类加载器,this.getClass().getClassLoader()
Class<?>[] interfaces: Class类型的数组,表示代理类要实现的接口列表, target.getClass().getInterfaces()
InvocationHandler h: (将方法调用分派到的调用处理程序)实现这个接口,创建代理对象,写增强的方法,this
2.没有接口情况,使用Cglib动态代理
创建子类代理对象实现增强
AOP实现
Spring一般都是基于AspectJ实现AOP操作,AspectJ不是Spring组成部分
切入点表达式作用:知道对类里面哪个方法进行增强
execution([权限修饰符][返回类型][全类名][方法名] ([参数列表]))
execution(* example.service...(..))
1. 基于xml配置文件实现
<aop:config>
<aop:aspect ref="logCut02">
<aop:pointcut id="cut" expression="execution (* example.service..*.*(..))"/>
<aop:before method="before" pointcut-ref="cut"/>
<aop:after method="after" pointcut-ref="cut"/>
<aop:after-returning method="afterReturn" pointcut-ref="cut"/>
<aop:after-throwing method="afterThrow" pointcut-ref="cut" throwing="e"/>
<aop:around method="around" pointcut-ref="cut"/>
</aop:aspect>
</aop:config>
2. 基于注解方式实现
-
1.创建增强类 -
2.进行通知的配置 -
-
a.开启注解扫描
-
-
-
b.使用注解创建被代理对象和代理对象
-
-
-
c.在代理类上面@AspectJ
-
-
-
d.Spring配置文件中开启生成代理对象
-
<aop:aspectj-autoproxy/>
五种不同类型的通知
// 切入点抽取
// @Pointcut("execution(* example.service..*.*(..))")
public void cut() {}
// 方法之前
@Before(value = "cut()")
// 方法返回结果之后
@AfterReturning(value = "cut()")
// 方法之后
@After(value = "cut()")
@AfterThrowing(value = "cut()", throwing = "e")
// before之前 after之前 方法前后
@Around(value = "cut()")
增强类优先级
增强类上面@Order(数字),数字值越小,优先级越高
完全注解开发
@EnableAspectJAutoProxy
作者介绍

luckydog
V1