SpringBoot 注解实现AOP功能,日志记录,操作留痕等等

实现对指定接口进行拦截,横向插入自己的自定义逻辑内容

1. 创建一个自定义注解当做切面

可以按自己的需要创建多个参数使用,我这里为了举例子就写了一个。

package com.a.b.common.utils.operationrecord;

import java.lang.annotation.*;

@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Operation {
    String operationType() default "";
}

2. 创建切面,对拦截(添加了注解的接口)到的内容进行处理

可以通过方法获取请求参数、返回参数、和自定义注解的参数,这里我就不写这么多了,只写了一个获取自定义注解的参数。

package com.a.b.common.utils.operationrecord;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;

/**
 * @program: h6dp-parent
 * @description:
 * @author:
 * @create: 2023-02-08 14:23
 **/
@Aspect
@Component
public class OperationAspect {

	//设置切点
    @Pointcut("@annotation(Operation)")
    public void operationCut() {
    }
    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     * @param jsonResult 接口返回值
     */
    @AfterReturning(pointcut = "operationCut()", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Object jsonResult) {
        //获取自定义注解的值
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        Operation operation = signature.getMethod().getDeclaredAnnotation(Operation.class);
        System.out.println("operationType " + operation.operationType());
        System.out.println("joinPoint " + jsonResult);
    }

    @Around(value = "operationCut()")
    public void doAround(ProceedingJoinPoint joinPoint) {
        System.out.println("joinPoint " + joinPoint);
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e         异常
     */
    @AfterThrowing(pointcut = "operationCut()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Exception e) {

    }
}

3. 配置目标,在想要拦截的接口上添加注解

配置目标,在需要拦截的接口上写上刚才的自定义注解,整个流程就算完成了,之后运行项目看
配置拦截

4. 最终效果

最终结果

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值