---
title: "寻找spring框架的启动入口 ContextLoaderListener"
author: "duyunfengsolo"
date: "2010-06-21T21:58:58Z"
tags: []
categories: ["企业架构"]
slug: "spring-contextloaderlistener"
draft: false
lastmod: "2010-06-21T21:58:58Z"
id: 695980
url: "https://solodu.iteye.com/blog/695980"
---

spring在web下的入口在配置文件web.xml的监听器中

&lt;listener&gt;

        &lt;listener-class&gt;

           org.springframework.web.context.ContextLoaderListener

        &lt;/listener-class&gt;

&lt;/listener&gt;

&lt;context-param&gt;

     &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;

      &lt;param-value&gt;classpath:conf/spring/applicationContext.xml&lt;/param-value&gt;

&lt;/context-param&gt;

上述是在web.xml中的配置信息。

 

 

//实现了接口ServletContextListener,也就是说他必须实现contextDestroyed, contextInitialized这两个方法

public class ContextLoaderListener implements [ServletContextListener]() {

       private ContextLoader contextLoader;

       /\**

       * Initialize the root web application context.

       \*/

//Spring框架由此启动, contextInitialized也就是监听器类的main入口函数

       public void [contextInitialized]()(ServletContextEvent event) {

              this.contextLoader = createContextLoader();

              this.contextLoader.initWebApplicationContext(event.getServletContext());

       }

       /\**

       * Create the ContextLoader to use. Can be overridden in subclasses.

       * @return the new ContextLoader

       \*/                                            

       protected ContextLoader createContextLoader() {

              return new ContextLoader();

       }

       /\**

       * Return the ContextLoader used by this listener.

       * @return the current ContextLoader

       \*/

       public ContextLoader getContextLoader() {

              return this.contextLoader;

       }

       /\**

       * Close the root web application context.

       \*/

       public void [contextDestroyed]()(ServletContextEvent event) {

              if (this.contextLoader != null) {

                     this.contextLoader.closeWebApplicationContext(event.getServletContext());

              }

       }

}

 

总的来说这个入口非常简单,所有实现都隐藏在ContextLoader类里,我们在下一篇的内容中讨论ContextLoader,如果你不知道为什么这里是程序的入口,那么复习一下[ServletContextListener]() 接口和监听器的相关知识吧