【Spring】RequestContextHolderの概要

6058 ワード

Web開発では、サービス層やツールクラスでHttpServeretRequestオブジェクトを取得する必要があるのは一般的です.1つの方法は、HttpServiceletRequestを方法のパラメータとしてcontroller層からずっと下ろして伝達することであるが、これは少し骨が折れ、優雅ではない.もう1つはRequestContextHolderで、必要な場所で直接次の方法でHttpServertRequestを取ればいいです.コードは以下の通りです.
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
        .getRequestAttributes()).getRequest();

なぜこのように使用できるのかを理解するには、2つの問題を理解する必要があります.
  • RequestContextHolderが現在のHttpServeretRequest
  • を取得できる理由
  • HttpServertRequestはいつRequestContextHolder
  • に設定されますか?
    1つ目の問題について、ThreadLocalに詳しい人は、これがThreadLocalの応用であることを簡単に見ることができるはずです.このような原理は、前のブロガー(ThreadLocal原理)で述べたように、実は前のブロガーの文末に述べたUserContextHolderに似ています.
    2つ目の問題はspring-mvcの問題に属するべきで、これはspring-mvcの実行時に設定されたものです
    ソース分析
    まず、RequestContextHolderのソースコードを見てみましょう.ソースコードは次のとおりです.
    public abstract class RequestContextHolder  {
    
        private static final ThreadLocal requestAttributesHolder =
                new NamedThreadLocal("Request attributes");
    
        private static final ThreadLocal inheritableRequestAttributesHolder =
                new NamedInheritableThreadLocal("Request context");
    
    
        public static void resetRequestAttributes() {
            requestAttributesHolder.remove();
            inheritableRequestAttributesHolder.remove();
        }
    
    
        public static void setRequestAttributes(RequestAttributes attributes) {
            setRequestAttributes(attributes, false);
        }
    
        // RequestAttributes     ThreadLocal , HttpServletRequest HttpServletResponse     RequestAttributes   ,      RequestAttributes     。              RequestAttributes  ,    RequestAttributes            HttpServletRequest  
        public static void setRequestAttributes(RequestAttributes attributes, boolean inheritable) {
            if (attributes == null) {
                resetRequestAttributes();
            }
            else {
                if (inheritable) {
                    inheritableRequestAttributesHolder.set(attributes);
                    requestAttributesHolder.remove();
                }
                else {
                    requestAttributesHolder.set(attributes);
                    inheritableRequestAttributesHolder.remove();
                }
            }
        }
    
        public static RequestAttributes getRequestAttributes() {
            RequestAttributes attributes = requestAttributesHolder.get();
            if (attributes == null) {
                attributes = inheritableRequestAttributesHolder.get();
            }
            return attributes;
        }
    
    }
    

    ではspring-mvcでどのように実現されているのか、簡単に分析してみましょう.具体的なメカニズムを知りたいならspring-mvcのソースコードを見てみましょう.
    FrameworkServiceというクラス、すなわちDispatcherServiceの親クラスを見てみると、プロセスリクエストメソッドがあり、メソッド名によってリクエストを処理するためのメソッドであることがわかります.
    protected final void processRequest(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            long startTime = System.currentTimeMillis();
            Throwable failureCause = null;
    
            LocaleContext previousLocaleContext = LocaleContextHolder.getLocaleContext();
            LocaleContext localeContext = buildLocaleContext(request);
    
            RequestAttributes previousAttributes = RequestContextHolder.getRequestAttributes();
            ServletRequestAttributes requestAttributes = buildRequestAttributes(request, response, previousAttributes);
    
            WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
            asyncManager.registerCallableInterceptor(FrameworkServlet.class.getName(), new RequestBindingInterceptor());
    
            // RequestAttributes   RequestContextHolder
            initContextHolders(request, localeContext, requestAttributes);
    
            try {
                //       
                doService(request, response);
            }
            catch (ServletException ex) {
                failureCause = ex;
                throw ex;
            }
            catch (IOException ex) {
                failureCause = ex;
                throw ex;
            }
            catch (Throwable ex) {
                failureCause = ex;
                throw new NestedServletException("Request processing failed", ex);
            }
    
            finally {
                //  RequestContextHolder    RequestAttributes
                resetContextHolders(request, previousLocaleContext, previousAttributes);
                if (requestAttributes != null) {
                    requestAttributes.requestCompleted();
                }
    
                if (logger.isDebugEnabled()) {
                    if (failureCause != null) {
                        this.logger.debug("Could not complete request", failureCause);
                    }
                    else {
                        if (asyncManager.isConcurrentHandlingStarted()) {
                            logger.debug("Leaving response open for concurrent processing");
                        }
                        else {
                            this.logger.debug("Successfully completed request");
                        }
                    }
                }
    
                publishRequestHandledEvent(request, response, startTime, failureCause);
            }
        }
        
        
        private void initContextHolders(
                HttpServletRequest request, LocaleContext localeContext, RequestAttributes requestAttributes) {
    
            if (localeContext != null) {
                LocaleContextHolder.setLocaleContext(localeContext, this.threadContextInheritable);
            }
            if (requestAttributes != null) {
                RequestContextHolder.setRequestAttributes(requestAttributes, this.threadContextInheritable);
            }
            if (logger.isTraceEnabled()) {
                logger.trace("Bound request context to thread: " + request);
            }
        }
    

    ソースコードを簡単に見ると、HttpService RequestはdoServiceメソッドを実行する前、すなわち特定のビジネスロジックを実行する前に設定され、ビジネスロジックを実行した後、または例外を投げ出したときにRequestContextHolderをリセットして現在のHttpService Requestを削除することがわかります.
    本文を書く目的は主にこのRequestContextHolderの使用を記録し、今後ビジネスコードの中でこのツールを巧みに使って自分のコードをより簡潔で優雅にしたいということです.