注入一个组件类
@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;
}