zoukankan      html  css  js  c++  java
  • Spring Boot使用AOP在控制台打印请求、响应信息

    AOP称为面向切面编程,在程序开发中主要用来解决一些系统层面上的问题,比如日志,事务,权限等。

    AOP简介

    AOP全称Aspect Oriented Programming,面向切面,AOP主要实现的目的是针对业务处理过程中的切面进行提取,它所面对的是处理过程中的某个步骤或阶段,以获得逻辑过程中各部分之间低耦合性的隔离效果。其与设计模式完成的任务差不多,是提供另一种角度来思考程序的结构,来弥补面向对象编程的不足。

      通俗点讲就是提供一个为一个业务实现提供切面注入的机制,通过这种方式,在业务运行中将定义好的切面通过切入点绑定到业务中,以实现将一些特殊的逻辑绑定到此业务中。

      比如,现在需要打印请求、响应信息,很多地方有需要,这时候又不能把代码复制一遍,所有需要AOP来实现。

    常用注解说明

    @Aspect -- 作用是把当前类标识为一个切面供容器读取
    @Pointcut -- (切入点):就是带有通知的连接点,在程序中主要体现为书写切入点表达式
    @Before -- 标识一个前置增强方法,相当于BeforeAdvice的功能
    @AfterReturning -- 后置增强,相当于AfterReturningAdvice,方法退出时执行
    @AfterThrowing -- 异常抛出增强,相当于ThrowsAdvice
    @After -- final增强,不管是抛出异常或者正常退出都会执行
    @Around -- 环绕增强,相当于MethodInterceptor

    pom.xml中引入AOP的jar包

    <!-- aop -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>
            <!-- fastjson -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.47</version>
    </dependency>

    切面类代码

    package com.example.helloSpringBoot.aop;

    import com.alibaba.fastjson.JSON;
    import org.aspectj.lang.ProceedingJoinPoint;
    import org.aspectj.lang.annotation.Around;
    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.annotation.Pointcut;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.context.request.RequestAttributes;
    import org.springframework.web.context.request.RequestContextHolder;
    import org.springframework.web.context.request.ServletRequestAttributes;

    import javax.servlet.http.HttpServletRequest;

    /**
     * 切面 打印请求、返回参数信息
     */
    @Aspect // 定义一个切面
    @Configuration
    public class LogRecordAspect {
        private static final Logger logger = LoggerFactory.getLogger(LogRecordAspect.class);

        // 定义切点Pointcut
        @Pointcut("execution(* com.example.helloSpringBoot.controller.*Controller.*(..))")
        public void excudeService() {
        }

        @Around("excudeService()")
        public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
            RequestAttributes ra = RequestContextHolder.getRequestAttributes();
            ServletRequestAttributes sra = (ServletRequestAttributes) ra;
            HttpServletRequest request = sra.getRequest();

            String method = request.getMethod();
            String uri = request.getRequestURI();
            String paraString = JSON.toJSONString(request.getParameterMap());
            logger.info("***************************************************");
            logger.info("请求开始, URI: {}, method: {}, params: {}", uri, method, paraString);

            // result的值就是被拦截方法的返回值
            Object result = pjp.proceed();
            logger.info("请求结束,controller的返回值是 " + JSON.toJSONString(result));
            return result;
        }
    }

    测试打印结果

    浏览器分别访问 http://localhost:8080/hello?a=1&b=2 和http://localhost:8080/hello?c=11&d=22,控制台打印结果如下:

    ***************************************************
    请求开始, URI: /hello, method: GET, params: {"a":["1"],"b":["2"]}
    请求结束,controller的返回值是 "hello spring boot!"
    ***************************************************
    请求开始, URI: /hello, method: GET, params: {"c":["11"],"d":["22"]}
    请求结束,controller的返回值是 "hello spring boot!"

    下面的是我的公众号二维码图片,欢迎关注,欢迎留言,一起学习,一起进步。

  • 相关阅读:
    资源与锁
    资源与锁
    Leetcode-Rotate List
    Leetcode-Unique Paths II
    Leetcode-Unique Paths
    Leetcode-Minimum Path Sum
    Leetcode-Sqrt(x)
    Leetcode-Set Matrix Zeroes
    Leetcode-Search a 2D Matrix
    Leetcode-Combinations
  • 原文地址:https://www.cnblogs.com/haha12/p/10405839.html
Copyright © 2011-2022 走看看