• 自定义注解用AOP实现接口信息打印


    导入boot项目的aop依赖

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

    定义注解

    import java.lang.annotation.*;
    
    /**
     * web日志注解
     */
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.METHOD})
    @Documented
    public @interface WebLog {
    
        /**
         * 日志描述信息
         *
         * @return
         */
        String description() default "";
    }

    注解实现类

    import com.alibaba.fastjson.JSON;
    import lombok.extern.slf4j.Slf4j;
    import org.aspectj.lang.JoinPoint;
    import org.aspectj.lang.ProceedingJoinPoint;
    import org.aspectj.lang.annotation.Around;
    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.annotation.Before;
    import org.aspectj.lang.annotation.Pointcut;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.context.request.RequestContextHolder;
    import org.springframework.web.context.request.ServletRequestAttributes;
    
    import javax.servlet.http.HttpServletRequest;
    import java.lang.reflect.Method;
    import java.util.Objects;
    
    @Aspect
    @Configuration
    @Slf4j
    public class WebLogAspect {
    
        /**
         * 以自定义@WebLog注解为切点
         */
        @Pointcut("@annotation(com.hd.demo.common.aop.WebLog)")
        public void webLog() {
        }
    
        /**
         * 环绕
         *
         * @return java.lang.Object
         * @params [pjp]
         * @description
         */
        @Around("webLog()")
        public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
            long startTime = System.currentTimeMillis();
            Object result = pjp.proceed();
            if (!(result instanceof ResponseEntity)) {
                log.info("Response Args  : {}", JSON.toJSONString(result));
                log.info("Time-Consuming : {}", System.currentTimeMillis() - startTime);
            }
    
            return result;
        }
    
    
        /**
         * 在切点之前记录
         *
         * @return void
         * @params [joinPoint]
         * @description
         */
        @Before("webLog()")
        public void doBefore(JoinPoint joinPoint) throws Exception {
            // 开始打印请求日志
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = Objects.requireNonNull(attributes).getRequest();
            // 获取 @WebLog 注解的描述信息
            String methodDescription = getAspectLogDescription(joinPoint);
            // 打印请求相关参数
            log.info("======================================== Start ==========================================");
            // 打印请求 url
            log.info("URL            : {}", request.getRequestURL().toString());
            // 打印描述信息
            log.info("Description    : {}", methodDescription);
            // 打印 Http method
            log.info("HTTP Method    : {}", request.getMethod());
            // 打印调用 controller 的全路径以及执行方法
            log.info("Class Method   : {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
            // 打印请求的 IP
            log.info("IP             : {}", request.getRemoteAddr());
            // 打印请求入参
            log.info("Request Args   : {}",  JSON.toJSONString(joinPoint.getArgs()));
        }
    
        /**
         * 获取切面注解的描述
         *
         * @param joinPoint 切点
         * @return 描述信息
         * @throws Exception
         */
        public String getAspectLogDescription(JoinPoint joinPoint) throws Exception {
            String targetName = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            Object[] arguments = joinPoint.getArgs();
            Class targetClass = Class.forName(targetName);
            Method[] methods = targetClass.getMethods();
            StringBuilder description = new StringBuilder();
            for (Method method : methods) {
                if (method.getName().equals(methodName)) {
                    Class[] clazzs = method.getParameterTypes();
                    if (clazzs.length == arguments.length) {
                        description.append(method.getAnnotation(WebLog.class).description());
                        break;
                    }
                }
            }
            return description.toString();
        }
    }
  • 相关阅读:
    MAC 卡顿耗电发热问题解决
    MAC Homebrew 安装SVN等失败
    ArcGIS Server手工删除缓存导致地图服务崩溃
    (译)Web地图设计模式——ArcGIS Server
    JQuery & ASP.NET结合使用文章推荐
    ESRI提供的一个Silverlight地图示例
    冰墩墩python代码
    Mysql MAX,WHERE和 GROUP BY 三个关键字同时使用 执行顺序以及查询错位的问题
    06 IO流 05File的常用方法 + 序列化 + 反序列化 + transient + 序列化版本号 + IO和Properties联合使用
    06 多线程 02线程安全 + 解决线程安全问题
  • 原文地址:https://www.cnblogs.com/21-Gram/p/11274952.html
Copyright © 2020-2023  润新知