Spring Aop

papa1. 引入依赖

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

2.创建切面

@Component
@Aspect
@Slf4j
public class AopAspect {

  

}

3.创建切点

可以定义get post方法 也可以定义普通的方法

第一个 * 代表返回值

.*代表方法名

(..)代表随意参数也可以指定类型

    @Pointcut("@annotation(org.springframework.web.bind.annotation.GetMapping)")
    public void getLog(){}
    @Pointcut("@annotation(org.springframework.web.bind.annotation.PostMapping)")
    public void postLog(){}
    @Pointcut("execution(* com.example.aa.service.test.*(..))")
    public void sum(){}

    @Pointcut("execution(* com.example.aa.service.test.*(int))")
    @Pointcut("execution(* com.example.aa.service.test.*(com.example.User))")
    @Pointcut("execution(* com.example.aa.service.test.*(java.lang.String))")

4.创建通知

可以通过参数获得方法名,参数等,也可以通过request获得请求的url,类型等

 @Before("sum() || postLog()")
    public void bf(JoinPoint point){
        //获得方法名
        String name = point.getSignature().getName();
        //获得参数
        Object[] args = point.getArgs();
        String s = Arrays.toString(args);
        //使用log日志
        log.info("日志输出")

        System.out.println("执行前置通知"+name+s);
    }

环绕通知通过这个方法 joinPoint.proceed() 执行原方法 返回值为obj

 @Around("execution(* com.example.service.*.*(..))")
    public Object handleException(ProceedingJoinPoint joinPoint) throws Throwable {
        try {
            return joinPoint.proceed();
        } catch (Exception e) {
            // 在这里处理异常,例如记录日志、进行补偿操作等
            System.out.println("Exception occurred in method: " + joinPoint.getSignature().getName() + ", Message: " + e.getMessage());
            // 您可以根据需要抛出一个自定义的异常,或者返回一个默认值
            throw new CustomException("An error occurred while processing the method.");
        }
    }

抛出异常后通知

 @Around("execution(* com.example.service.*.*(..))")
    public Object handleException(ProceedingJoinPoint joinPoint) throws Throwable {
        try {
            return joinPoint.proceed();
        } catch (Exception e) {
            // 在这里处理异常,例如记录日志、进行补偿操作等
            System.out.println("Exception occurred in method: " + joinPoint.getSignature().getName() + ", Message: " + e.getMessage());
            // 您可以根据需要抛出一个自定义的异常,或者返回一个默认值
            throw new CustomException("An error occurred while processing the method.");
        }
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值