• 自定义注解打印日志与耗时


            在项目执行中针对一些方法需要重复增加log与耗时打印等,此处用Spring Aop环绕增强实现。非常简单,步骤如下:

    1、自定义注解

    1. @Documented //注解修饰会被Javadoc处理,注解会在文档中生成
    2. @Target(ElementType.METHOD)//定义注解作用范围,参考ElementType枚举,此处作用在方法上
    3. @Retention(RetentionPolicy.RUNTIME)//定义注解生命周期,参考RetentionPolicy枚举,此处参与代码逻辑
    4. @Inherited//定义注解是否可以被继承,此处酌情处理
    5. public @interface LogMsg {
    6. //自定义方法名称,默认为方法名
    7. String name();
    8. }

    2、定义切面类

    1. @Slf4j//log相关
    2. @Component//作为组件交给spring管理
    3. @Aspect//定义为切面类
    4. public class LogMsgAop {
    5. //定义切点,此处以注解为切点
    6. @Pointcut("@annotation(com.hs.LogMsg)")
    7. public void logPoint() {
    8. }
    9. //定义环绕增强作用在定义好的切点处
    10. @Around("logPoint()")
    11. public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
    12. MethodSignature pointSignature = (MethodSignature) joinPoint.getSignature();
    13. Method method = pointSignature.getMethod();
    14. LogMsg annotation = method.getAnnotation(LogMsg.class);
    15. //获取注解中的name或者方法名
    16. String msgPre = StringUtils.isBlank(annotation.name()) ? method.getName() : annotation.name();
    17. Object[] args = joinPoint.getArgs();
    18. String[] parameterNames = pointSignature.getParameterNames();
    19. StringBuilder sb = new StringBuilder();
    20. for (int i = 0; i < parameterNames.length; i++) {
    21. if (i > 0) {
    22. sb.append(",");
    23. }
    24. sb.append(parameterNames[i]);
    25. sb.append(":");
    26. sb.append(args[i]);
    27. }
    28. log.info("{}方法入参:{}", msgPre, sb.toString());
    29. long start = System.currentTimeMillis();
    30. //默认执行方法
    31. Object result = joinPoint.proceed(args);
    32. log.info("{}方法出参:{},耗时:{}ms", msgPre, result, System.currentTimeMillis() - start);
    33. return result;
    34. }
    35. }

    3、在需要打印日志的方法上使用

    @LogMsg(name = "这是一个测试方法")

  • 相关阅读:
    【redis漏洞复现】Redis getshell的几种方式
    VMD结合ISSA优化LSSVM功率预测
    LeetCode算法心得——和可被 K 整除的子数组(前缀和+HashMap)
    计算机毕业设计node.js+vue+Web移动端外卖平台
    解释 Git 的基本概念和使用方式
    如何使用IDEA导入Maven项目
    打印机 默认使用 首选项配置
    常见的旅游类软文类型分享
    小程序容器技术加快推动国产操作系统“上车”
    论文翻译:《Phosvardeep:使用序列信息对磷酸变化的深度学习预测》
  • 原文地址:https://blog.csdn.net/asd372506589/article/details/133183738