Spring AOP
AOP相关概念
-
joinPoint
连接点,横切织入点
-
pointCut
切点,指定符合条件的一组
joinPoint
表达形式:
(1)指定
joinPoint
所在方法名称(2)正则表达式
(3)特定的
pointCut
表述语言 -
advice
织入到连接点的横切逻辑
(1)
beforeAdvice
(2)
afterAdvice
,包括afterReturningAdvice
、afterThrowingAdvice
(3)
aroundAdvice
-
aspect
对很切关注点逻辑进行模块化封装的AOP概念实体
Spring AOP
动态代理和字节码增强技术来实现,在程序运行期间为目标对象生成代理对象,将横切逻辑加入到代理对象中
静态代理
动态代理
JDK
动态代理
基于
Proxy
类和InvocationHandler
接口实现,为实现了相应接口的目标对象生成代理对象实例。
Proxy
用来生成动态代理实例,InvocationHandler
实现横切点逻辑。
对于没有实现任何接口的目标对象,使用
cglib
为目标对象生成动态代理对象实例。
cglib
动态代理
生成目标对象的子类,对目标对象进行重写扩展功能。
Enhancer用来动态生成目标对象的子类,
MethodInterceptor
接口完成横切逻辑
实际应用
1.定义切面类(类上加注解@Aspect
、@EnableAspectJAutoProxy
)
@Aspect
,告诉spring
哪个类是切面类
@EnableAspectJAutoProxy
,开启基于注解的aop模式
(1)切面类的方法上标注通知注解,写切入点表达式,匹配业务逻辑类方法
@Pointcut("@annotation(com.*.*.AnnotationInterface)")
@PointCut("execution(* com.*.*.service.*.methodName(..))")
(2)通知方法
前置通知(@Before
):在目标方法运行前运行
后置通知(@After
):在目标方法运行结束之后运行
返回通知(@AfterReturning
):目标方法正常返回后运行
异常通知(@AfterThrowing
):出现异常时运行
环绕通知(@Around
):手动推进目标方法运行(joinPoint.procced
)
@Aspect
@EnableAspectJAutoProxy
public class CustomAspect {
@Before("pointCut()")
public void beforeMethod(JoinPoint joinPoint){}
@After(value = "pointcut()")
public void afterMethod() {
}
@AfterReturning(value = "pointCut()", returning = "returnValue")
public void afterReturning(JoinPoint joinPoint, Object returnValue) {
}
@AfterThrowing(value = "pointCut()", throwing = "e")
public void afterThrowing(RuntimeException e){}
@Around(value = "pointCut()")
public void aroundMethod(ProceedingJoinPoint point){
}
}