定义一个通用的切面

@Aspect
@Component
public class SearchCenterServiceAspect {
private static final Logger logger = LoggerFactory.getLogger(SearchCenterServiceAspect.class);

/**
* 用来记录请求进入的时间,防止多线程时出错
*/
private ThreadLocal<Long> startTime = new ThreadLocal<>();


/**
* 定义切入点,controller下面的所有类的所有公有方法
*/
@Pointcut("execution(public * com.xxx.service.bus.*.*(..))")
public void point() {
}


/**
* 方法之前执行,日志打印请求信息
* @param joinPoint
*/
@Before("point()")
public void doBefore(JoinPoint joinPoint) {
logger.info("request=" + getMethodNameAndArgs(joinPoint));
}


@After("point()")
public void doAfter() {
long endTime = System.currentTimeMillis();
}

/**
* 方法返回之前执行
* @param object
*/
@AfterReturning(returning = "object", pointcut = "point()")
public void doAfterReturning(JoinPoint joinPoint, Object object) {
}

/**
* 获取方法名和参数
* @param joinPoint
* @return
*/
private String getMethodNameAndArgs(JoinPoint joinPoint) {
Object[] args = joinPoint.getArgs();
StringBuffer sb = new StringBuffer("methodName:");
sb.append(joinPoint.getTarget().getClass().getName() + "."
+ joinPoint.getSignature().getName() + "(");
for (int i = 0; i < args.length; i++) {
sb.append("arg[" + i + "]: " + args[i] + ",");
}
if (args.length > 0) {
sb.deleteCharAt(sb.length() - 1);
}
sb.append(")");
return sb.toString();
}

}

posted on 2021-07-13 17:12  小小鸟儿!  阅读(104)  评论(0编辑  收藏  举报