spring 中Aop的使用注解完成通知的使用

1.引入aop依赖

<!--    aop依赖-->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.9.7</version>
    </dependency>

2.开启包扫描

<context:component-scan base-package="cn.kgc.spring"></context:component-scan>

3.使用aop开启注解

 <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

 4.创建切面类使用注解

package cn.kgc.spring.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

/*
@author peng
@date4/7/2022
切面类: 可以添加各种类型的通知
*/
@Component
@Aspect  //标记当前类时通知类
public class AllAdvice {
    //实现切点表达式的复用
    @Pointcut("execution(* *(..))")
    public void all(){

    }
    //前置通知
    @Before("all()")
    public void before() {
        System.out.println("---前置通知---");
    }

    //后置通知
    @AfterReturning("execution(* *(..))")
    public void afterReturning() {

        System.out.println("-------------后置通知---------------");

    }

    //最终通知 不管核心业务是否有异常 均要执行
    @After(("execution(* *(..))"))
    public void after() {

        System.out.println("-------------最终通知---------------");

    }

    //异常通知 核心业务出现异常时添加的通知 没有异常不添加
    @AfterThrowing(("execution(* *(..))"))
    public void afterThrowing() {
        System.out.println("---异常通知---");
    }

    //环绕通知
    @Around(("execution(* *(..))"))
    public Object around(ProceedingJoinPoint proceedingJoinPoint) {
        try {
            System.out.println("---环绕前置通知---");
            Object proceed = proceedingJoinPoint.proceed();
            System.out.println("---环绕后置通知---");
            return proceed;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            System.out.println("---环绕异常通知---");
        } finally {
            System.out.println("---环绕最终通知---");
        }
        return null;
    }

}

5.运行结果

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值