SpringBoot AOP

256 阅读2分钟

转载

仅作为工具使用,不涉及原理、教程。
代码转载自【码神之路】项目实战教程,springboot+vue练手级项目,真实的在线博客系统,十年大厂程序员讲解,从易到难,循序渐进_哔哩哔哩_bilibili

大佬文章

SpringBoot使用AOP_大老杨的博客
SpringBoot中的AOP使用_彤彤的小跟班的博客
Spring-AOP切入点表达式详解_夏志121的博客

可用代码

使用注解对单个方法进行织入,比较灵活。
如需批量执行使用传统方式定义,看上面大佬的那篇文章。

依赖

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

自定义注解

import java.lang.annotation.*;

/**
 * 日志注解
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LogAnnotation {

    String module() default "";

    String operation() default "";
}

日志切面(仅供参考)

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * 日志切面
 *
 */
@Aspect
@Component
@Slf4j
public class LogAspect {


    @Pointcut("@annotation( 自定义注解完整路径 )")
    public void logPointCut() {
    }

    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long beginTime = System.currentTimeMillis();
        //执行方法
        Object result = point.proceed();
        //执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;
        //保存日志
        recordLog(point, time);
        return result;
    }

    private void recordLog(ProceedingJoinPoint joinPoint, long time) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        LogAnnotation logAnnotation = method.getAnnotation(LogAnnotation.class);
        log.info("=====================log start================================");
        log.info("module:{}",logAnnotation.module());
        log.info("operation:{}",logAnnotation.operation());

        //请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        log.info("request method:{}",className + "." + methodName + "()");

        //请求的参数
        Object[] args = joinPoint.getArgs();
        String params = JSON.toJSONString(args[0]);
        log.info("params:{}",params);

        //获取request 设置IP地址
        
        log.info("excute time : {} ms",time);
        log.info("=====================log end================================");
    }

}

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface OperLog {

    /*操作模块*/
    public ModuleEnum title() ;

    /*操作类型*/
    public OperTypeEnum operType();

}
@Around("@annotation(operLog)")
public Object recordOperLog(ProceedingJoinPoint point,OperLog operLog) throws Throwable {
    operLog.title().toString()
}

注解使用

@PostMapping
    //加上此注解 代表要对此接口记录日志
    @LogAnnotation(module="文章",operator="获取文章列表")
    public Result listArticle(@RequestBody PageParams pageParams){
        return articleService.listArticle(pageParams);
    }

相关问题

在一个方法内部调用其他被代理的方法时,被调用方法的 AOP 将不起作用

解决方法

((目标类) AopContext.currentProxy()).目标方法

目标方法必须为public,否则无法加载上下文环境。