spring Aop 一点通

本文深入解析Spring AOP的基本概念及工作原理,介绍了基于注解的配置方式,详细说明了不同类型的增强处理及其执行顺序,并提供了具体的代码示例。

一 基本概念

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的名称

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值