侧边栏壁纸
博主头像
这就是之谦博主等级

我们的征途是星辰大海

  • 累计撰写 182 篇文章
  • 累计创建 3 个标签
  • 累计收到 16 条评论
标签搜索

目 录CONTENT

文章目录

SpringAOP的日志切入实战

这就是之谦
2022-11-20 / 0 评论 / 0 点赞 / 616 阅读 / 339 字
温馨提示:
本文最后更新于 2022-11-20,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

SpringBoot 整合AOP

依赖pom

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

Controller层

@RestController
public class HelloController {

    @RequestMapping("/hello")
    public String hello(@RequestParam("id") Long id){
        System.out.println("this is hello");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        return id + ":hello Ydd:"+ format.format(new Date());
    }
}

Aspect

import com.alibaba.fastjson.JSON;
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.reflect.Method;

/**
 * @author liuxuewei
 */
@Component
@Aspect
public class HelloAspect {

    @Pointcut(" execution(* com.example.demo0927.HelloController.*(..)) & " +
            " @within(org.springframework.web.bind.annotation.RequestMapping)")
    public void requestPointCut() {

    }

    @Before("requestPointCut()")
    public void before() {
        System.out.println("before--------------");
    }

    @After("requestPointCut()")
    public void after() {
        System.out.println("after-----------------");
    }

    @Around("requestPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        aroundBefore(point);
        Object returnData = point.proceed();//around 前和后的分隔
        aroundAfter(point,returnData);
        return returnData;
    }

    private void aroundBefore(ProceedingJoinPoint point) {//环绕前的操作,打入参log
        System.out.println("around before");
        String title = getTitle(point);
        Object[] args = point.getArgs();
        if (args != null && args.length > 0) {
            for (Object arg : args) {
                System.out.println(title + "接口入参:" + JSON.toJSONString(arg));//log
            }
        }

    }

    private void aroundAfter(ProceedingJoinPoint point, Object returnData) {//环绕后的操作,打出参log
        System.out.println("around after");
        System.out.println(returnData);//log
    }

    private String getTitle(ProceedingJoinPoint point) {
        Signature signature = point.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        String className = signature.getDeclaringTypeName();
        Method currentMethod = methodSignature.getMethod();
        //如果有swagger的话,直接取swagger的name
//        ApiOperation apiOperation = currentMethod.getAnnotation(ApiOperation.class);
//        if (apiOperation != null) {
//            return apiOperation.value();
//        }
        return className + "#" + currentMethod.getName();
    }

}

0

评论区