AOP的应用-spring切面编程-@Aspect

注入一个组件类

@Aspect
@Component

参数:

/** 切面表达式
 *  execution 代表所要执行的表达式主题
 *  第一处 * 代表方法返回类型 *代表所有类型
 *  第二处  包名代表aop监控的类所在的包
 *  第三处 .. 代表该包及其子包下的所有类方法
 *  第四处 * 代表类名,*代表所有类
 *  第五处 *(..) *代表类中的方法名,(..)表示方法中的任何参数
 *  */

定义一个切点:指定打印切入点在那个包的代码。(可以是service层也可以是controller层)

/** 定义一个切点 */
@Pointcut("execution(public * com.ainilzb.*.controller..*Controller.*(..))")

也可以和切面直接使用:

@Around("execution(* com.ainilzb.service.impl..*.*(..))")
public Object recordTimeLog(ProceedingJoinPoint joinPoint) throws Throwable {}

结合log日志打印controller、service内容:

controller

@Around("controllerPointcut()")
public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    long startTime = System.currentTimeMillis();
    Object result = proceedingJoinPoint.proceed();
    // 排除字段,敏感字段或太长的字段不显示
    String[] excludeProperties = {"password", "shard"};
    PropertyPreFilters filters = new PropertyPreFilters();
    PropertyPreFilters.MySimplePropertyPreFilter excludefilter = filters.addFilter();
    excludefilter.addExcludes(excludeProperties);
    LOG.info("返回结果: {}", JSONObject.toJSONString(result, excludefilter));
    LOG.info("------------- 结束 耗时:{} ms -------------", System.currentTimeMillis() - startTime);
    return result;
}

service

@Around("execution(* com.ainilzb.service.impl..*.*(..))")
public Object recordTimeLog(ProceedingJoinPoint joinPoint) throws Throwable {
    log.info("===== 开始执行 {}.{} =====",
            joinPoint.getTarget().getClass(),
            joinPoint.getSignature().getName()
    );
    // 开始时间
    long begin = System.currentTimeMillis();
    Object result = joinPoint.proceed();
    //结束时间
    long end = System.currentTimeMillis();
    //时间差
    long takeTime = end - begin;
    if (takeTime > 3000) {
        log.error("===== 执行结束,耗时:{} 毫秒 =====", takeTime);
    } else if (takeTime > 2000) {
        log.warn("===== 执行结束,耗时:{} 毫秒 =====", takeTime);
    } else {
        log.info("===== 执行结束,耗时:{} 毫秒 =====", takeTime);
    }
    return result;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值