一 基本概念
Aspect 切面 :通常是一个类 定义了通知和切点
(JoinPoint) 连接点: 目标方法
(Advice) 通知:before after afterReturning afterThrowing around
(PointCut) 切点: 一般是一个表达式
二 Spring Aop
Spring中的Aop代理离不开Spring的IOC容器,代理的生成,管理与依赖关系都是由IOC容器负责,Spring默认使用JDK动态代理,在需要代理类而不是代理接口的时候能够,Spring会切换成CGLIB代理。
三 基于注解的Aop配置
1 启用@AspectJ支持
代码块
XML
<aop:aspectj-autoproxy />
2 通知类型介绍
Before 在目标方法被调用前增强处理 @Before需要指定切点表达式
AfterReturning 在目标方法正常完成后增强 @AfterReturning 除了指定切点 还可以指定一个返回值形参returning,代表目标方法的返回值
AfterThrowing 处理抛出的异常,@AfterThrowing 除了指定切点,还可以指定一个throwing的返回值 通过这个形参访问异常对象
After 目标完成后做增强 不管是成功还是异常。
Around 环绕目标方法 目标方法完成前后做增强处理
3 切面类
代码块
Java
@Component
@Aspect
public class DemoAspect {
@PointCut("execution(* demo.A.*(..))")
public void pointcut() {} //这个只是为了指代PointCut 没什么内容
@Before("pointcut()")
public void deBefore(JointPoint joinPoint) {
System.out.println("Aop Before Advice..");
}
@After("pointcut()")
public void doAfter(JointPoint joinPoint) {
System.out.println("Aop After Advice..");
}
@AfterReturning(pointcut="pointcut()", returning="returnVal")
public void afterReturn(JointPoint joinPoint, Object returnVal) {
System.out.println("Aop AfterReturning Advice :" + returnVal);
}
@AfterThrowing(pointcut="pointcut()", throwing="error")
public void afterThrowing(JointPoint joinPoint, Throwable error) {
System.out.println("Aop AfterThrowing Advice :" + error);
}
@Around("pointcut()")
public void around(ProceedingJointPoint pjp) {
System.out.println("Aop Before Advice.."); //Before处理
try {
pjp.proceed(); //目标方法的执行
} catch (Throwable e) {
e.printStackTrace(); //AfterThrowing处理
}
System.out.println("After Advice"); //After处理
}
}
4 通知执行的优先级
进入目标方法 先织入Around 然后是Before 退出目标时,先Around,在AfterReturning 最后才After
5 切点表达式
execution (返回值 类.方法(方法参数))
* 匹配任意的值 .. 零个或多个
execution 指定执行方法 within限定连接点 this指定类型实例 bean指定IOC容器的bean的名称