怎么写切面
@Aspect @Component @Order(1000) public class RequestContextAspect { @Around("execution(* com.ymm.trade.*.web.rest..*(..))") public Object around(ProceedingJoinPoint joinPoint) throws Throwable { try{ HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest(); RequestContext requestContext = build(request); RequestContextUtils.setRequestContext(requestContext); Object result = joinPoint.proceed(); RequestContextUtils.resetRequestContext(); return result; }catch (Throwable throwable){ RequestContextUtils.resetRequestContext(); throw throwable; } } public RequestContext build(HttpServletRequest request){ String clientInfoStr = request.getHeader("Client-Info"); String userAgentStr = request.getHeader("user-agent"); AuthorizationUserDTO user = AuthorizationUserContext.currentAuthorizationUserDTO(); if(Objects.isNull(user)){ return new RequestContext(clientInfoStr, userAgentStr, 0L, 0); }else{ // todo receive loginFrom from clientInfoStr return new RequestContext(clientInfoStr, userAgentStr, user.getUserId(), 0); } } }
其中 RequestContextUtils
public class RequestContextUtils { public RequestContextUtils(){ } private static ThreadLocal<RequestContext> requestContextThreadLocal = new ThreadLocal(); public static void resetRequestContext(){ requestContextThreadLocal.remove(); } public static void setRequestContext(RequestContext requestContext){ requestContextThreadLocal.set(requestContext); } public static RequestContext getRequestContext(){ return requestContextThreadLocal.get(); } }