Spring AOP 简单使用

1. 添加依赖

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

2. 配置切面

2.1 AOP 一些术语

  • 目标对象(Target):需要被增强的方法
  • 连接点(JoinPoint):程序执行的某个特殊位置,如某个方法调用前,调用后,方法抛出异常后,这些代码中的特定点称为连接点。简单来讲,就在目标对象的哪个位置进行增强
  • 切点(Pointcut):每个目标对象的连接点有多个,如何定位到某个感兴趣的连接点,就需要通过切点来定位。简单来讲:就是通过切点找到指定的连接点位置。
  • 增强(Advice):织入到目标对象特定连接点上的一段代码。简单来讲,就是在目标对象的特点连接点上的增强代码
  • 织入(Weaving): 织入就是将增强代码添加到对目标对象具体连接点上的过程。
  • 切面(Aspect): 切面由切点和增强组成,它既包括了横切逻辑的定义,也包括了连接点的定义,SpringAOP就是将切面所定义的横切逻辑织入到切面所制定的连接点中。

2.2 配置切面类

@Pointcut("execution(public * com.zhihong.web..*.*(..))")
    public void point() {}

    @Before("point()")
    public void doBefore() {
        System.out.println("Before");
    }

    @After("point()")
    public void commit() {
        System.out.println("After");
    }

    @AfterReturning(value = "point()", returning = "returnObject")
    public void afterReturning(JoinPoint joinPoint, Object returnObject) {
        System.out.println("AfterReturning");
    }

    @AfterThrowing("point()")
    public void afterThrowing() {
        System.out.println("afterThrowing afterThrowing  rollback");
    }

    @Around("point()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        try {
            System.out.println("around try");
            return joinPoint.proceed();
        } catch (Throwable e) {
            e.printStackTrace();
            throw e;
        } finally {
            System.out.println("around finally");
        }
}

执行顺序:around try > before > around finally > after > afterReturning

2.3 常用AOP通知(增强)类型

  • before(前置通知):在执行目标方法前做些操作,比如获取连接对象
  • after(后置通知):在执行目标方法后做些操作,无论是否发生异常,它都会执行,比如关闭连接对象
  • afterReturning(返回通知):在执行目标方法后无异常,会执行的操作
  • afterThrowing(异常通知):在目标方法抛出异常后执行
  • around(环绕通知):在方法目标方法执行前和执行后都会执行

2.4 利用自定义注解使用AOP

2.4.1 自定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAspectAnnotation {

}
2.4.2 切面配置
@Aspect
@Component
public class MyAspectService {

    @Before("@annotation(MyAspectAnnotation)")
    public void doBefore() {
        System.out.println("开启事务");
    }

    @AfterReturning(value = "@annotation(MyAspectAnnotation)", returning = "returnObject")
    public void afterReturning(JoinPoint joinPoint, Object returnObject) {
        System.out.println("提交事务");
    }

    @AfterThrowing("@annotation(MyAspectAnnotation)")
    public void afterThrowing() {
        System.out.println("回滚事务");
    }
}
2.4.3 自定义注解的使用
@GetMapping("/getUser")
    @MyAspectAnnotation
    public User getUser(Integer id) {
        return userService.getUserById(id);
}

result:
 开启事务
 ......   
 提交事务
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值