• 怎么写切面


    @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();
        }
    }
  • 相关阅读:
    在centos7上使用packstack安装openstack
    解决 React-Native: Android project not found. Maybe run react-native android first?
    javascript_11-函数面试题
    javascript_10-函数
    前端面试记录NO.1
    javascript_09-数组
    javascript_08-while 和 do while
    javascript_07-break 和 continue
    javascript_05-操作符
    javascript_06-控制流程
  • 原文地址:https://www.cnblogs.com/juniorMa/p/15827738.html
Copyright © 2020-2023  润新知