自定义spring AOP增强
自定义一个注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SysLog {
String value() default "";
}
AOP实现
@Aspect
@Component
public class SysLogAspect {
private static final Logger logger = LoggerFactory.getLogger(SysLogAspect.class);
//SysLog 自定义注解的全限定类名
@Pointcut("@annotation(SysLog)")
public void logPointCut() {
}
@Around("logPointCut()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
long beginTime = System.currentTimeMillis();
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
SysLog syslog = method.getAnnotation(SysLog.class);
String title = syslog.value();
if (title.equals("")) {
String className = joinPoint.getTarget().getClass().getName();
String methodName = signature.getName();
title = className + "." + methodName + "()";
}
StringBuilder startSbf = new StringBuilder("===> ");
startSbf.append(title).append("请求开始");
Object[] args = joinPoint.getArgs();
if (args.length == 1) startSbf.append(",请求参数:").append(JSONObject.toJSONString(args[0]));
logger.info(startSbf.toString());
Object result = joinPoint.proceed();
logger.info("<=== " + title + "请求结束,响应参数:" + JSONObject.toJSONString(result) + ",请求耗时:" + (System.currentTimeMillis() - beginTime));
return result;
}
}