自定义注解,插入日志

注解的意思写在上一篇文章(笔记,给自己记录)

先创建一个注解类(简单点就写个title,可以写很多字段描述)

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

    String title() default "";
}

做一个切面,来使用这个注解(也可以在filter中判断,使用)切面的注解之前的文章可以翻出来看

@Aspect
@Component
public class MytestAspect {

    private static final Logger log = LoggerFactory.getLogger(MytestAspect.class);

    // 配置织入点
    @Pointcut("@annotation(com.xxx.xxxx.Mytest)")
    public void MytestPointCut() {
    }

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "MytestPointCut()", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Object jsonResult)
    {
        handleLog(joinPoint, null, jsonResult);
    }

    protected void handleLog(final JoinPoint joinPoint, final Exception e, Object jsonResult)
    {
        try {
            // 获得注解
            Mytest annotationLog = getAnnotationLog(joinPoint);
            if (annotationLog == null)
            {
                return;
            }

            //获取注解信息
            String title = annotationLog.title();
            //打印一下

            log.debug("============title信息:{}", title);

            //获取用户信息(这个是登录的时候设置的)
            Long currentUserId = UserUtil.getCurrentUserId();




            //获取到注解上面的信息就可以插进日志表了

        }catch (Exception ex){

        }


    }

    /**
     * 是否存在注解,如果存在就获取
     */
    private Mytest getAnnotationLog(JoinPoint joinPoint) throws Exception
    {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method != null)
        {
            return method.getAnnotation(Mytest.class);
        }
        return null;
    }
}

然后再需要加上日志的请求的方法加上这个注解

    @Mytest(title = "首页轮播图")
    @GetMapping("listImg")
    public Result<List<IndexImg>> listImg(){
        return new Result<List<IndexImg>>().ok(rbListService.listImg());
    }

请求一下,看看打印结果

2020-01-08 15:15:27.115 DEBUG 8624 --- [nio-8989-exec-1] com.xxx.xxx.utils.MytestAspect    : ============title信息:首页轮播图

另外还可以获取当前注解的方法名称

 String className = joinPoint.getTarget().getClass().getName();
 String methodName = joinPoint.getSignature().getName();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值