ホームページ Java &#&チュートリアル Spring Web の開始時に IOC ソース コードを分析する

Spring Web の開始時に IOC ソース コードを分析する

Mar 12, 2017 am 09:40 AM

この記事では、Spring Web の起動時の IOC ソース コードの調査を分析します

  1. IOC を調査するには、まず Web で単純な Web プロジェクトを作成し、Web コンテナーが起動すると、まず ContextLoaderListener クラスに入り、 applicationContext.xml ファイルはクラスパスの下にあります。次に、ContextLoaderListener に焦点を当て、オープン ソース コード

    <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
        </context-param>
    
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
    ログイン後にコピー

をクリックします。これには、主に ServletContextListener

インターフェース

の 2 つの実装メソッドが含まれています。 Web コンテナは、まず contextInitialized メソッドを呼び出し、tomcat によってカプセル化されたコンテナ リソースを渡し、次に親クラスの初期化コンテナ メソッドを呼び出します。

/**
     * Initialize the root web application context.     */
    @Override    public void contextInitialized(ServletContextEvent event) {
        initWebApplicationContext(event.getServletContext());
    }    /**
     * Close the root web application context.     */
    @Override    public void contextDestroyed(ServletContextEvent event) {
        closeWebApplicationContext(event.getServletContext());
        ContextCleanupListener.cleanupAttributes(event.getServletContext());
    }
ログイン後にコピー

このメソッドの主なステップは、XmlWebApplicationContext のルート コンテナーを作成するために使用される createWebApplicationContext メソッドです。このコンテナーは servletContextEvent から取得されます。

loadParentContext メソッドは、親コンテナをロードするために使用されます。メイン メソッドの configureAndRefreshWebApplicationContext は、ルート コンテナの構成と更新に使用されます。メソッド内の最も重要なメソッドは、最も重要な機能を実装する refresh メソッドです。

/*** The root WebApplicationContext instance that this loader manages.*/private WebApplicationContext context;public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
      ...........省略// Store context in local instance variable, to guarantee that            // it is available on ServletContext shutdown.
            if (this.context == null) {                this.context = createWebApplicationContext(servletContext);
            }            if (this.context instanceof ConfigurableWebApplicationContext) {
                ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;                if (!cwac.isActive()) {                    // The context has not yet been refreshed -> provide services such as                    // setting the parent context, setting the application context id, etc
                    if (cwac.getParent() == null) {                        // The context instance was injected without an explicit parent ->                        // determine parent for root web application context, if any.
                        ApplicationContext parent = loadParentContext(servletContext);
                        cwac.setParent(parent);
                    }
                    configureAndRefreshWebApplicationContext(cwac, servletContext);
                }
            }
            servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);

            ClassLoader ccl = Thread.currentThread().getContextClassLoader();            if (ccl == ContextLoader.class.getClassLoader()) {
                currentContext = this.context;
            }            else if (ccl != null) {
                currentContextPerThread.put(ccl, this.context);
            }
  ......省略            return this.context;
        
    }
ログイン後にコピー

prepareRefreshメソッドは、後で使用する環境を準備するために使用されます。

obtainFreshBeanFactory メソッドは beanFactory を取得します

@Override    public void refresh() throws BeansException, IllegalStateException {        synchronized (this.startupShutdownMonitor) {            // Prepare this context for refreshing.            prepareRefresh();            // Tell the subclass to refresh the internal bean factory.
            ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();            // Prepare the bean factory for use in this context.            prepareBeanFactory(beanFactory);            try {                // Allows post-processing of the bean factory in context subclasses.                postProcessBeanFactory(beanFactory);                // Invoke factory processors registered as beans in the context.                invokeBeanFactoryPostProcessors(beanFactory);                // Register bean processors that intercept bean creation.                registerBeanPostProcessors(beanFactory);                // Initialize message source for this context.                initMessageSource();                // Initialize event multicaster for this context.                initApplicationEventMulticaster();                // Initialize other special beans in specific context subclasses.                onRefresh();                // Check for listener beans and register them.                registerListeners();                // Instantiate all remaining (non-lazy-init) singletons.                finishBeanFactoryInitialization(beanFactory);                // Last step: publish corresponding event.                finishRefresh();
            }            catch (BeansException ex) {
                logger.warn("Exception encountered during context initialization - cancelling refresh attempt", ex);                // Destroy already created singletons to avoid dangling resources.                destroyBeans();                // Reset &#39;active&#39; flag.                cancelRefresh(ex);                // Propagate exception to caller.
                throw ex;
            }
        }
    }
ログイン後にコピー

実際に返される beanFactory はその実装クラス DefaultListableBeanFactory であり、後で XML でインスタンス化されたクラスをロードするためにインスタンス化されます。

loadBeanDefinitions は実際にクラスをロードするために使用される重要なメソッドです。これまでのものはすべて

準備作業

でした。

以上がSpring Web の開始時に IOC ソース コードを分析するの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)