在项目执行中针对一些方法需要重复增加log与耗时打印等,此处用Spring Aop环绕增强实现。非常简单,步骤如下:
1、自定义注解
@Documented //注解修饰会被Javadoc处理,注解会在文档中生成
@Target(ElementType.METHOD)//定义注解作用范围,参考ElementType枚举,此处作用在方法上
@Retention(RetentionPolicy.RUNTIME)//定义注解生命周期,参考RetentionPolicy枚举,此处参与代码逻辑
@Inherited//定义注解是否可以被继承,此处酌情处理
public @interface LogMsg {
//自定义方法名称,默认为方法名
String name();
}
2、定义切面类
@Slf4j//log相关
@Component//作为组件交给spring管理
@Aspect//定义为切面类
public class LogMsgAop {
//定义切点,此处以注解为切点
@Pointcut("@annotation(com.hs.LogMsg)")
public void logPoint() {
}
//定义环绕增强作用在定义好的切点处
@Around("logPoint()")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
MethodSignature pointSignature = (MethodSignature) joinPoint.getSignature();
Method method = pointSignature.getMethod();
LogMsg annotation = method.getAnnotation(LogMsg.class);
//获取注解中的name或者方法名
String msgPre = StringUtils.isBlank(annotation.name()) ? method.getName() : annotation.name();
Object[] args = joinPoint.getArgs();
String[] parameterNames = pointSignature.getParameterNames();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < parameterNames.length; i++) {
if (i > 0) {
sb.append(",");
}
sb.append(parameterNames[i]);
sb.append(":");
sb.append(args[i]);
}
log.info("{}方法入参:{}", msgPre, sb.toString());
long start = System.currentTimeMillis();
//默认执行方法
Object result = joinPoint.proceed(args);
log.info("{}方法出参:{},耗时:{}ms", msgPre, result, System.currentTimeMillis() - start);
return result;
}
}
3、在需要打印日志的方法上使用
@LogMsg(name = "这是一个测试方法")