自定义注解+AOP切面 实现接口访问日志

AOP+自定义注解实现接口访问日志

原创,请勿转载!!!!!
要是实现了,帮忙点个赞!!!!!

目录

1、准备自定义注解;
2、AOP切面注解;
3、实现效果。

1、准备自定义注解;

package com.inter.my;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
//作用于方法
@Target(ElementType.METHOD)
//运行时有效
@Retention(RetentionPolicy.RUNTIME)
public @interface YinXing{

    //描述方法
    String log() default "YinXing Log日志";

}

2、AOP切面注解;

package com.inter.aspect;

import com.inter.my.YinXing;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author yinxing
 * @date 2022-09-08
 */
@Aspect
@Component
@Slf4j
public class LogAspect {

    @Around("@annotation(YinXing)")
    public Object around(ProceedingJoinPoint point, YinXing yinXing) throws Throwable {
        //通过切入点获取目标class对象
        Class<?> aClass = point.getTarget().getClass();
        //获取接入点的类名
        String className = aClass.getName();
        //获取目标方法名称
        String methodName = point.getSignature().getName();
        //获取MyLog注解的value参数
        String value = yinXing.value();
        //拿到方法的入参
        Object[] args = point.getArgs();
        StringBuffer stringBuffer = new StringBuffer();
        for (Object arg : args) {
            Map<String, Object> argMap = (Map<String, Object>) arg;
            stringBuffer.append(arg).append("\\");
        }
        UUID uuid = UUID.randomUUID();
        log.info("\n======YinXing Log-{}," +
                "类名[{}]," +
                "方法名[{}]" +
                "注解值:[{}]" +
                "参数:[{}]",uuid,className,methodName,value,stringBuffer);
        long startTime = System.currentTimeMillis();
        //运行目标方法
        Object[] objects =new Object[1];
        Map<String, Object> argMap = new HashMap<>();
        argMap.put("message","AOP消息");
        objects[0] = argMap;
        Object proceed = point.proceed(objects);
        long endTime = System.currentTimeMillis();
        log.info("\n======YinXing Log-{}," +
                "类名[{}]," +
                "方法名[{}]" +
                "注解值:[{}]" +
                "耗时:[{}ms]" +
                "返回参数:[{}]",uuid,className,methodName,value,endTime-startTime,proceed.toString());
        return proceed;
    }

}

3、实现效果。

自定义注解+AOP切面 实现接口访问日志_第1张图片

你可能感兴趣的:(aop,java,spring,mybatis)