使用注解+Aop实现单个方法的日志记录

设计思路:使用自定义注解加在方法上,这个注解被AOP管理,当方法运行时注解得到信息,注解的信息又可以被AOP得到,在AOP中将注解的信息存放到数据库。

实现如下:
自定义的注解可以自定义属性,基本属性可以是:descript(方法描述),type(crud哪种类型)

/**
 * author:lcy
 * since 2021/6/19 16:12
 * @Target(ElementType.METHOD)表示在方法上生效
 * @Retention(RetentionPolicy.RUNTIME)表示运行时生效
 * @Documented 说明该注解将包含在javadoc中
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyLogAnnotation {
    public String descript() default "";
    public String type() default "";
}

实现一个切面(aspect),切入点(pointcut)是自定义的注解,通知(advice)类型必须是环绕,必须是环绕的原因是连接点(joincut)的类型是ProceedingJoinPoint而不是JoinPoint。

/**
 * author:lcy
 * since 2021/6/19 16:16
 */
@Aspect
@Component
public class MyLogAspect {
    @Pointcut("@annotation(com.general.aspect.annotation.MyLogAnnotation)")
    public void MyAop(){
    }
    @Around("MyAop()")
    public Object saveLog(ProceedingJoinPoint joinPoint) throws Throwable {
        //反射通过target得到该类的全路径
        String fullClassPath = joinPoint.getTarget().getClass().getName();
        //反射通过signature得到该类的该方法
        String runTimeMethod = joinPoint.getSignature().getName();
        //aop得到运行结果
        Object proceed = joinPoint.proceed();
        //通过类名得到该对象
        Class<?> aClass = Class.forName(fullClassPath);
        //得到该类的所有方法
        Method[] methods = aClass.getMethods();
        //遍历方法
        for (Method method : methods) {
            //遍历的方法和该方法名一致则通过getAnnotation拿到该注解
            if(method.getName().equals(runTimeMethod)){
                MyLogAnnotation annotation = method.getAnnotation(MyLogAnnotation.class);
                //方法路径加名称
                System.out.println(fullClassPath);
                //注解的type类型
                System.out.println(annotation.type());
                //注解的descript描述
                System.out.println(annotation.descript());
                //注解的返回数据
                System.out.println(proceed);
                //在这里可以将信息保存到数据库
                //service.save(log)
            }
        }
        return null;
    }
}

最后在controller类中需要的方法上加上这个注解就可以了

/**
 * @author lcy
 * @Description
 * @since 2021/6/17 14:34
 */
@Controller
public class GeneralController {
    @RequestMapping("/index")
    @ResponseBody
    @MyLogAnnotation(descript = "什么什么操作",type = "增删改查的哪一个")
    public String index(){
        Result<Object> result = new Result<>();
        result.setResult("成功");
        result.setCode(200);
        result.setMessage("成功了");
        String data = JSON.toJSONString(result);
        return data;
    }
}

访问localhost:8080/index时运行台出现下面信息
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值