本文主要讲述AOP在mall项目中的应用,通过在controller层建了一个切面来实现接口访问的统一日志记录。

AOP

AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。

AOP的相关术语

通知(Advice)

通知描述了切面要完成的工作以及何时执行。比如我们的日志切面需要记录每个接口调用时长,就需要在接口调用前后分别记录当前时间,再取差值。

  • 前置通知(Before):在目标方法调用前调用通知功能;

  • 后置通知(After):在目标方法调用之后调用通知功能,不关心方法的返回结果;

  • 返回通知(AfterReturning):在目标方法成功执行之后调用通知功能;

  • 异常通知(AfterThrowing):在目标方法抛出异常后调用通知功能;

  • 环绕通知(Around):通知包裹了目标方法,在目标方法调用之前和之后执行自定义的行为。

连接点(JoinPoint)

通知功能被应用的时机。比如接口方法被调用的时候就是日志切面的连接点。

切点(Pointcut)

切点定义了通知功能被应用的范围。比如日志切面的应用范围就是所有接口,即所有controller层的接口方法。

切面(Aspect)

切面是通知和切点的结合,定义了何时、何地应用通知功能。

引入(Introduction)

在无需修改现有类的情况下,向现有的类添加新方法或属性。

织入(Weaving)

把切面应用到目标对象并创建新的代理对象的过程。

Spring中使用注解创建切面

相关注解

  • @Aspect:用于定义切面

  • @Before:通知方法会在目标方法调用之前执行

  • @After:通知方法会在目标方法返回或抛出异常后执行

  • @AfterReturning:通知方法会在目标方法返回后执行

  • @AfterThrowing:通知方法会在目标方法抛出异常后执行

  • @Around:通知方法会将目标方法封装起来

  • @Pointcut:定义切点表达式

切点表达式

指定了通知被应用的范围,表达式格式:

execution(方法修饰符 返回类型 方法所属的包.类名.方法名称(方法参数)
//com.macro.mall.tiny.controller包中所有类的public方法都应用切面里的通知execution(public * com.macro.mall.tiny.controller.*.*(..))//com.macro.mall.tiny.service包及其子包下所有类中的所有方法都应用切面里的通知execution(* com.macro.mall.tiny.service..*.*(..))//com.macro.mall.tiny.service.PmsBrandService类中的所有方法都应用切面里的通知execution(* com.macro.mall.tiny.service.PmsBrandService.*(..))

添加AOP切面实现接口日志记录

添加日志信息封装类WebLog

用于封装需要记录的日志信息,包括操作的描述、时间、消耗时间、url、请求参数和返回结果等信息。

  1. package com.macro.mall.tiny.dto;


  2. /**

  3. * Controller层的日志封装类

  4. * Created by macro on 2018/4/26.

  5. */

  6. public class WebLog {

  7.    /**

  8.     * 操作描述

  9.     */

  10.    private String description;


  11.    /**

  12.     * 操作用户

  13.     */

  14.    private String username;


  15.    /**

  16.     * 操作时间

  17.     */

  18.    private Long startTime;


  19.    /**

  20.     * 消耗时间

  21.     */

  22.    private Integer spendTime;


  23.    /**

  24.     * 根路径

  25.     */

  26.    private String basePath;


  27.    /**

  28.     * URI

  29.     */

  30.    private String uri;


  31.    /**

  32.     * URL

  33.     */

  34.    private String url;


  35.    /**

  36.     * 请求类型

  37.     */

  38.    private String method;


  39.    /**

  40.     * IP地址

  41.     */

  42.    private String ip;


  43.    /**

  44.     * 请求参数

  45.     */

  46.    private Object parameter;


  47.    /**

  48.     * 请求返回的结果

  49.     */

  50.    private Object result;


  51.    //省略了getter,setter方法

  52. }

添加切面类WebLogAspect

定义了一个日志切面,在环绕通知中获取日志需要的信息,并应用到controller层中所有的public方法中去。

  1. package com.macro.mall.tiny.component;


  2. import cn.hutool.core.util.StrUtil;

  3. import cn.hutool.core.util.URLUtil;

  4. import cn.hutool.json.JSONUtil;

  5. import com.macro.mall.tiny.dto.WebLog;

  6. import io.swagger.annotations.ApiOperation;

  7. import org.aspectj.lang.JoinPoint;

  8. import org.aspectj.lang.ProceedingJoinPoint;

  9. import org.aspectj.lang.Signature;

  10. import org.aspectj.lang.annotation.*;

  11. import org.aspectj.lang.reflect.MethodSignature;

  12. import org.slf4j.Logger;

  13. import org.slf4j.LoggerFactory;

  14. import org.springframework.core.annotation.Order;

  15. import org.springframework.stereotype.Component;

  16. import org.springframework.util.StringUtils;

  17. import org.springframework.web.bind.annotation.RequestBody;

  18. import org.springframework.web.bind.annotation.RequestParam;

  19. import org.springframework.web.context.request.RequestContextHolder;

  20. import org.springframework.web.context.request.ServletRequestAttributes;


  21. import javax.servlet.http.HttpServletRequest;

  22. import java.lang.reflect.Method;

  23. import java.lang.reflect.Parameter;

  24. import java.util.ArrayList;

  25. import java.util.HashMap;

  26. import java.util.List;

  27. import java.util.Map;


  28. /**

  29. * 统一日志处理切面

  30. * Created by macro on 2018/4/26.

  31. */

  32. @Aspect

  33. @Component

  34. @Order(1)

  35. public class WebLogAspect {

  36.    private static final Logger LOGGER = LoggerFactory.getLogger(WebLogAspect.class);


  37.    @Pointcut("execution(public * com.macro.mall.tiny.controller.*.*(..))")

  38.    public void webLog() {

  39.    }


  40.    @Before("webLog()")

  41.    public void doBefore(JoinPoint joinPoint) throws Throwable {

  42.    }


  43.    @AfterReturning(value = "webLog()", returning = "ret")

  44.    public void doAfterReturning(Object ret) throws Throwable {

  45.    }


  46.    @Around("webLog()")

  47.    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {

  48.        long startTime = System.currentTimeMillis();

  49.        //获取当前请求对象

  50.        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

  51.        HttpServletRequest request = attributes.getRequest();

  52.        //记录请求信息

  53.        WebLog webLog = new WebLog();

  54.        Object result = joinPoint.proceed();

  55.        Signature signature = joinPoint.getSignature();

  56.        MethodSignature methodSignature = (MethodSignature) signature;

  57.        Method method = methodSignature.getMethod();

  58.        if (method.isAnnotationPresent(ApiOperation.class)) {

  59.            ApiOperation apiOperation = method.getAnnotation(ApiOperation.class);

  60.            webLog.setDescription(apiOperation.value());

  61.        }

  62.        long endTime = System.currentTimeMillis();

  63.        String urlStr = request.getRequestURL().toString();

  64.        webLog.setBasePath(StrUtil.removeSuffix(urlStr, URLUtil.url(urlStr).getPath()));

  65.        webLog.setIp(request.getRemoteUser());

  66.        webLog.setMethod(request.getMethod());

  67.        webLog.setParameter(getParameter(method, joinPoint.getArgs()));

  68.        webLog.setResult(result);

  69.        webLog.setSpendTime((int) (endTime - startTime));

  70.        webLog.setStartTime(startTime);

  71.        webLog.setUri(request.getRequestURI());

  72.        webLog.setUrl(request.getRequestURL().toString());

  73.        LOGGER.info("{}", JSONUtil.parse(webLog));

  74.        return result;

  75.    }


  76.    /**

  77.     * 根据方法和传入的参数获取请求参数

  78.     */

  79.    private Object getParameter(Method method, Object[] args) {

  80.        List<Object> argList = new ArrayList<>();

  81.        Parameter[] parameters = method.getParameters();

  82.        for (int i = 0; i < parameters.length; i++) {

  83.            //将RequestBody注解修饰的参数作为请求参数

  84.            RequestBody requestBody = parameters[i].getAnnotation(RequestBody.class);

  85.            if (requestBody != null) {

  86.                argList.add(args[i]);

  87.            }

  88.            //将RequestParam注解修饰的参数作为请求参数

  89.            RequestParam requestParam = parameters[i].getAnnotation(RequestParam.class);

  90.            if (requestParam != null) {

  91.                Map<String, Object> map = new HashMap<>();

  92.                String key = parameters[i].getName();

  93.                if (!StringUtils.isEmpty(requestParam.value())) {

  94.                    key = requestParam.value();

  95.                }

  96.                map.put(key, args[i]);

  97.                argList.add(map);

  98.            }

  99.        }

  100.        if (argList.size() == 0) {

  101.            return null;

  102.        } else if (argList.size() == 1) {

  103.            return argList.get(0);

  104.        } else {

  105.            return argList;

  106.        }

  107.    }

  108. }

进行接口测试

运行项目并访问:http://localhost:8080/swagger-ui.html

图片

可以看到控制住台中会打印如下日志信息:

{    "result": {        "code": 200,        "data": {            "total": 11,            "totalPage": 11,            "pageSize": 1,            "list": [{                "productCommentCount": 100,                "name": "万和",                "bigPic": "",                "logo": "http://macro-oss.oss-cn-shenzhen.aliyuncs.com/mall/images/20180607/timg(5).jpg",                "showStatus": 1,                "id": 1,                "sort": 0,                "productCount": 100,                "firstLetter": "W",                "factoryStatus": 1            }],            "pageNum": 1        },        "message": "操作成功"    },    "basePath": "http://localhost:8080",    "method": "GET",    "parameter": [{        "pageNum": 1    }, {        "pageSize": 1    }],    "description": "分页查询品牌列表",    "startTime": 1561273191861,    "uri": "/brand/list",    "url": "http://localhost:8080/brand/list",    "spendTime": 101}


更多相关文章

  1. 微软Edge浏览器准备内置屏蔽广告功能
  2. 微软分析Pypi数据: 5月21日Python3战胜Python2
  3. [简讯] 微软Linux子系统已经支持中文
  4. java漏洞成黑客目标微软呼吁用户更新软件

随机推荐

  1. Android的IPC机制Binder的详解汇总
  2. Android系统信息与安全机制
  3. Android(安卓)动态获取创建与删除文件权
  4. Android布局容器
  5. Android仿京东分类模块左侧分类条目效果
  6. Android之EditText指定类型数据
  7. Android.Documentation
  8. Android--应用开发2(AndroidManfest.xml)
  9. Belkin adds WeMo Light switch, looks t
  10. Android Training精要(二)開啟ActionBar的O